Skip to content

Commit 7105cab

Browse files
committed
[Server][Capability] Let setLazyLoading() defer loading into any supplied registry
Refs #495
1 parent bbfa001 commit 7105cab

8 files changed

Lines changed: 442 additions & 17 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ All notable changes to `mcp/sdk` will be documented in this file.
2626
* Tool, prompt and resource results and `TextContent` encode arrays and objects as compact JSON instead of pretty-printed JSON.
2727
* Fix the result of a retried `resources/read` leaving out the required `ttlMs` and `cacheScope`, which the TypeScript SDK's client rejects, or keeping the hints its handler set: it now always carries `ttlMs: 0` and `cacheScope: private`.
2828
* Fix tool name validation not following the spec's rule (1 to 128 characters of `A-Z`, `a-z`, `0-9`, `_`, `-` and `.`): names of 65 to 128 characters no longer log a warning, while names with a `/` or a trailing newline now do.
29+
* [BC Break] `Builder::setLazyLoading(true)` now also defers loading into a registry passed to `setRegistry()`, which any `RegistryInterface` supports. A registry you read directly stays empty until the server first reads it; without the call it is still loaded at build.
30+
* Add `DeferredRegistryInterface`, so the builder loads a custom registry without announcing the load as list changes, and no longer depends on the concrete `Registry`.
2931
* Split `RegistryInterface` by role into `ElementCatalogInterface`, `ElementResolverInterface` and `ElementWriterInterface`, which it extends. Request handlers depend on the role they use, so a handler can run against a catalog or resolver alone.
3032
* Add `Psr6SessionStore` and `Psr6NotificationBus`, which work like `Psr16SessionStore` and `Psr16NotificationBus` over a PSR-6 cache pool. `Builder::setDiscovery()` also accepts a PSR-6 pool as `$cache`.
3133
* Fix a nullable tool parameter with a default (e.g. `?string $category = 'books'`) receiving the default when the client explicitly sends `null`: `ReferenceHandler` now passes the `null` through.

‎docs/run/server-builder.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -430,8 +430,8 @@ $server = Server::builder()
430430
| `setSchemaGenerator()` | schemaGenerator | Replace the generator that builds input schemas from PHP types, see [Schema generation](../servers/schemas.md) |
431431
| `setSchemaValidator()` | schemaValidator | Replace the validator for tool arguments and structured output, see [Schema generation](../servers/schemas.md) |
432432
| `setReferenceHandler()` | referenceHandler | Replace the class that calls the handlers of tools, resources and prompts |
433-
| `setRegistry()` | registry | Use your own registry. It is loaded when the server is built |
434-
| `setLazyLoading()` | lazyLoading? | Load elements on the first registry read (default) or, with `false`, when the server is built |
433+
| `setRegistry()` | registry | Use your own registry. It is loaded when the server is built, unless you call `setLazyLoading()` |
434+
| `setLazyLoading()` | lazyLoading? | Load elements on the first registry read (default without `setRegistry()`) or, with `false`, when the server is built. Your own registry stays empty until the server first reads it |
435435
| `addLoader()` | loader | Add a custom loader that registers elements |
436436
| `addLoaders()` | loaders | Add several custom loaders |
437437
| `addRequestHandler()` | handler | Prepend a single custom request handler |
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the official PHP MCP SDK.
5+
*
6+
* A collaboration between Symfony and the PHP Foundation.
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Mcp\Capability;
13+
14+
use Mcp\Capability\Registry\Loader\LoaderInterface;
15+
16+
/**
17+
* A registry that takes part in its own load lifecycle.
18+
*
19+
* @author Christopher Hertel <mail@christopher-hertel.de>
20+
*/
21+
interface DeferredRegistryInterface
22+
{
23+
/**
24+
* Runs a pending load, if there is one. A failed load stays pending.
25+
*/
26+
public function load(): void;
27+
28+
/**
29+
* Runs $loader against this registry without announcing its writes as list changes, since they
30+
* describe the registry filling up rather than changing.
31+
*/
32+
public function loadFrom(LoaderInterface $loader): void;
33+
}

‎src/Capability/Registry.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
*
4141
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
4242
*/
43-
final class Registry implements RegistryInterface
43+
final class Registry implements RegistryInterface, DeferredRegistryInterface
4444
{
4545
/**
4646
* @var array<string, ToolReference>
Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the official PHP MCP SDK.
5+
*
6+
* A collaboration between Symfony and the PHP Foundation.
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Mcp\Capability\Registry;
13+
14+
use Mcp\Capability\DeferredRegistryInterface;
15+
use Mcp\Capability\Registry\Loader\LoaderInterface;
16+
use Mcp\Capability\RegistryInterface;
17+
use Mcp\Schema\Page;
18+
use Mcp\Schema\Prompt;
19+
use Mcp\Schema\ResourceDefinition;
20+
use Mcp\Schema\ResourceTemplate;
21+
use Mcp\Schema\Tool;
22+
23+
/**
24+
* Defers a loader over any registry to the first read, leaving the registry itself unaware of it.
25+
*
26+
* @internal
27+
*
28+
* @author Christopher Hertel <mail@christopher-hertel.de>
29+
*/
30+
final class LazyRegistry implements RegistryInterface, DeferredRegistryInterface
31+
{
32+
private bool $loaded = false;
33+
34+
public function __construct(
35+
private readonly RegistryInterface $registry,
36+
private readonly LoaderInterface $loader,
37+
) {
38+
}
39+
40+
public function load(): void
41+
{
42+
if ($this->loaded) {
43+
return;
44+
}
45+
46+
$this->loadFrom($this->loader);
47+
48+
$this->loaded = true;
49+
}
50+
51+
public function loadFrom(LoaderInterface $loader): void
52+
{
53+
if ($this->registry instanceof DeferredRegistryInterface) {
54+
$this->registry->loadFrom($loader);
55+
56+
return;
57+
}
58+
59+
$loader->load($this->registry);
60+
}
61+
62+
public function publishesListChanges(): bool
63+
{
64+
return $this->registry->publishesListChanges();
65+
}
66+
67+
public function registerTool(Tool $tool, callable|array|string $handler): ToolReference
68+
{
69+
return $this->registry->registerTool($tool, $handler);
70+
}
71+
72+
public function registerResource(ResourceDefinition $resource, callable|array|string $handler): ResourceReference
73+
{
74+
return $this->registry->registerResource($resource, $handler);
75+
}
76+
77+
public function registerResourceTemplate(ResourceTemplate $template, callable|array|string $handler, array $completionProviders = []): ResourceTemplateReference
78+
{
79+
return $this->registry->registerResourceTemplate($template, $handler, $completionProviders);
80+
}
81+
82+
public function registerPrompt(Prompt $prompt, callable|array|string $handler, array $completionProviders = []): PromptReference
83+
{
84+
return $this->registry->registerPrompt($prompt, $handler, $completionProviders);
85+
}
86+
87+
public function unregisterTool(string $name): void
88+
{
89+
$this->registry->unregisterTool($name);
90+
}
91+
92+
public function unregisterResource(string $uri): void
93+
{
94+
$this->registry->unregisterResource($uri);
95+
}
96+
97+
public function unregisterResourceTemplate(string $uriTemplate): void
98+
{
99+
$this->registry->unregisterResourceTemplate($uriTemplate);
100+
}
101+
102+
public function unregisterPrompt(string $name): void
103+
{
104+
$this->registry->unregisterPrompt($name);
105+
}
106+
107+
public function hasTool(string $name): bool
108+
{
109+
$this->load();
110+
111+
return $this->registry->hasTool($name);
112+
}
113+
114+
public function hasResource(string $uri): bool
115+
{
116+
$this->load();
117+
118+
return $this->registry->hasResource($uri);
119+
}
120+
121+
public function hasResourceTemplate(string $uriTemplate): bool
122+
{
123+
$this->load();
124+
125+
return $this->registry->hasResourceTemplate($uriTemplate);
126+
}
127+
128+
public function hasPrompt(string $name): bool
129+
{
130+
$this->load();
131+
132+
return $this->registry->hasPrompt($name);
133+
}
134+
135+
public function hasTools(): bool
136+
{
137+
$this->load();
138+
139+
return $this->registry->hasTools();
140+
}
141+
142+
public function hasResources(): bool
143+
{
144+
$this->load();
145+
146+
return $this->registry->hasResources();
147+
}
148+
149+
public function hasResourceTemplates(): bool
150+
{
151+
$this->load();
152+
153+
return $this->registry->hasResourceTemplates();
154+
}
155+
156+
public function hasPrompts(): bool
157+
{
158+
$this->load();
159+
160+
return $this->registry->hasPrompts();
161+
}
162+
163+
public function getTools(?int $limit = null, ?string $cursor = null): Page
164+
{
165+
$this->load();
166+
167+
return $this->registry->getTools($limit, $cursor);
168+
}
169+
170+
public function getResources(?int $limit = null, ?string $cursor = null): Page
171+
{
172+
$this->load();
173+
174+
return $this->registry->getResources($limit, $cursor);
175+
}
176+
177+
public function getResourceTemplates(?int $limit = null, ?string $cursor = null): Page
178+
{
179+
$this->load();
180+
181+
return $this->registry->getResourceTemplates($limit, $cursor);
182+
}
183+
184+
public function getPrompts(?int $limit = null, ?string $cursor = null): Page
185+
{
186+
$this->load();
187+
188+
return $this->registry->getPrompts($limit, $cursor);
189+
}
190+
191+
public function getTool(string $name): ToolReference
192+
{
193+
$this->load();
194+
195+
return $this->registry->getTool($name);
196+
}
197+
198+
public function getResource(string $uri, bool $includeTemplates = true): ResourceReference|ResourceTemplateReference
199+
{
200+
$this->load();
201+
202+
return $this->registry->getResource($uri, $includeTemplates);
203+
}
204+
205+
public function getResourceTemplate(string $uriTemplate): ResourceTemplateReference
206+
{
207+
$this->load();
208+
209+
return $this->registry->getResourceTemplate($uriTemplate);
210+
}
211+
212+
public function getPrompt(string $name): PromptReference
213+
{
214+
$this->load();
215+
216+
return $this->registry->getPrompt($name);
217+
}
218+
}

‎src/Server/Builder.php‎

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
namespace Mcp\Server;
1313

1414
use Mcp\Capability\Completion\ProviderInterface;
15+
use Mcp\Capability\DeferredRegistryInterface;
1516
use Mcp\Capability\Discovery\CachedDiscoverer;
1617
use Mcp\Capability\Discovery\Discoverer;
1718
use Mcp\Capability\Discovery\DiscovererInterface;
@@ -20,6 +21,7 @@
2021
use Mcp\Capability\Registry;
2122
use Mcp\Capability\Registry\Container;
2223
use Mcp\Capability\Registry\ElementReference;
24+
use Mcp\Capability\Registry\LazyRegistry;
2325
use Mcp\Capability\Registry\Loader\ChainLoader;
2426
use Mcp\Capability\Registry\Loader\DiscoveryLoader;
2527
use Mcp\Capability\Registry\Loader\ExplicitElementLoader;
@@ -273,7 +275,7 @@ final class Builder
273275

274276
private bool $hasCustomRegistry = false;
275277

276-
private bool $lazyLoading = true;
278+
private ?bool $lazyLoading = null;
277279

278280
private bool $headerValidation = true;
279281

@@ -576,8 +578,8 @@ public function setRegistry(RegistryInterface $registry): self
576578
*
577579
* Lazy (the default) defers loading to the first registry read so a persistent runtime does not
578580
* freeze the registry to a source not yet ready at build time. Disable to load eagerly at build.
579-
* A registry supplied via setRegistry() is always loaded eagerly; its own constructor loader,
580-
* if it has one, still runs on the first read.
581+
* A registry supplied via setRegistry() is loaded at build unless lazy loading is asked for explicitly.
582+
* Then it stays unloaded until the server first reads it, also for code holding the same instance.
581583
*/
582584
public function setLazyLoading(bool $lazyLoading = true): self
583585
{
@@ -1125,29 +1127,32 @@ private function resolve(): array
11251127

11261128
$chainLoader = new ChainLoader($loaders);
11271129

1128-
if ($this->hasCustomRegistry) {
1129-
// Builder can't inject the loader into an already-constructed instance, so load it eagerly.
1130-
// Via loadFrom(), which suppresses the change events the load would otherwise dispatch.
1130+
$prepopulated = null;
1131+
if ($this->hasCustomRegistry && true === $this->lazyLoading) {
1132+
$prepopulated = $this->registry;
1133+
$registry = new LazyRegistry($prepopulated, $chainLoader);
1134+
$eagerlyLoaded = false;
1135+
} elseif ($this->hasCustomRegistry) {
11311136
$registry = $this->registry;
1132-
if ($registry instanceof Registry) {
1137+
if ($registry instanceof DeferredRegistryInterface) {
11331138
$registry->loadFrom($chainLoader);
11341139
} else {
11351140
$chainLoader->load($registry);
11361141
}
11371142
$eagerlyLoaded = true;
11381143
} else {
1144+
$eagerlyLoaded = false === $this->lazyLoading;
11391145
$registry = new Registry($eventDispatcher, $logger, loader: $chainLoader);
1140-
if (!$this->lazyLoading) {
1146+
if ($eagerlyLoaded) {
11411147
$registry->load();
11421148
}
1143-
$eagerlyLoaded = !$this->lazyLoading;
11441149
}
11451150

11461151
$messageFactory = MessageFactory::make(additional: $this->extensionMessages);
11471152
// `server/discover` exists in the modern era only.
11481153
$modernMessageFactory = MessageFactory::make(additional: [...$this->extensionMessages, DiscoverRequest::class]);
11491154

1150-
$capabilities = $this->serverCapabilities ?? $this->detectCapabilities($registry, $eagerlyLoaded);
1155+
$capabilities = $this->serverCapabilities ?? $this->detectCapabilities($registry, $eagerlyLoaded, $prepopulated);
11511156

11521157
// Extensions enabled via enableExtension() are folded into caller-supplied
11531158
// capabilities too, so setCapabilities() does not silently drop them.
@@ -1203,8 +1208,9 @@ private function resolve(): array
12031208
* When loaded, capabilities are read from the registry. When deferred, reading it would force
12041209
* the load, so they are advertised from the configured sources instead — opaque sources (custom
12051210
* loaders, discovery) advertise all kinds, and over-advertising is harmless per MCP semantics.
1211+
* $prepopulated is a supplied registry waiting for its deferred load, safe to read directly.
12061212
*/
1207-
private function detectCapabilities(RegistryInterface $registry, bool $eagerlyLoaded): ServerCapabilities
1213+
private function detectCapabilities(RegistryInterface $registry, bool $eagerlyLoaded, ?RegistryInterface $prepopulated = null): ServerCapabilities
12081214
{
12091215
// Only the bus delivers list changes, and only if the registry publishes to it.
12101216
$listChanged = null !== $this->notificationBus && $registry->publishesListChanges();
@@ -1227,15 +1233,16 @@ private function detectCapabilities(RegistryInterface $registry, bool $eagerlyLo
12271233
}
12281234

12291235
$hasOpaqueSources = [] !== $this->loaders || null !== $this->discoveryBasePath;
1230-
$hasResources = [] !== $this->resources || [] !== $this->explicitResources || [] !== $this->resourceTemplates || [] !== $this->explicitResourceTemplates || $hasOpaqueSources;
1236+
$hasResources = [] !== $this->resources || [] !== $this->explicitResources || [] !== $this->resourceTemplates || [] !== $this->explicitResourceTemplates || $hasOpaqueSources
1237+
|| ($prepopulated?->hasResources() ?? false) || ($prepopulated?->hasResourceTemplates() ?? false);
12311238

12321239
return new ServerCapabilities(
1233-
tools: [] !== $this->tools || [] !== $this->explicitTools || $hasOpaqueSources,
1240+
tools: [] !== $this->tools || [] !== $this->explicitTools || $hasOpaqueSources || ($prepopulated?->hasTools() ?? false),
12341241
toolsListChanged: $listChanged,
12351242
resources: $hasResources,
12361243
resourcesSubscribe: $hasResources,
12371244
resourcesListChanged: $listChanged,
1238-
prompts: [] !== $this->prompts || [] !== $this->explicitPrompts || $hasOpaqueSources,
1245+
prompts: [] !== $this->prompts || [] !== $this->explicitPrompts || $hasOpaqueSources || ($prepopulated?->hasPrompts() ?? false),
12391246
promptsListChanged: $listChanged,
12401247
logging: true,
12411248
completions: true,

0 commit comments

Comments
 (0)