forked from modelcontextprotocol/php-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegistry.php
More file actions
481 lines (378 loc) · 13.4 KB
/
Copy pathRegistry.php
File metadata and controls
481 lines (378 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
<?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\Capability;
use Mcp\Capability\Registry\Loader\LoaderInterface;
use Mcp\Capability\Registry\PromptReference;
use Mcp\Capability\Registry\ResourceReference;
use Mcp\Capability\Registry\ResourceTemplateReference;
use Mcp\Capability\Registry\ToolReference;
use Mcp\Capability\Tool\NameValidator;
use Mcp\Event\PromptListChangedEvent;
use Mcp\Event\ResourceListChangedEvent;
use Mcp\Event\ResourceTemplateListChangedEvent;
use Mcp\Event\ToolListChangedEvent;
use Mcp\Exception\InvalidCursorException;
use Mcp\Exception\PromptNotFoundException;
use Mcp\Exception\ResourceNotFoundException;
use Mcp\Exception\ToolNotFoundException;
use Mcp\Schema\Page;
use Mcp\Schema\Prompt;
use Mcp\Schema\ResourceDefinition;
use Mcp\Schema\ResourceTemplate;
use Mcp\Schema\Tool;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Registry implementation that manages MCP element registration and access.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
final class Registry implements RegistryInterface
{
/**
* @var array<string, ToolReference>
*/
private array $tools = [];
/**
* @var array<string, ResourceReference>
*/
private array $resources = [];
/**
* @var array<string, PromptReference>
*/
private array $prompts = [];
/**
* @var array<string, ResourceTemplateReference>
*/
private array $resourceTemplates = [];
private bool $loaded = false;
private bool $loading = false;
public function __construct(
private readonly ?EventDispatcherInterface $eventDispatcher = null,
private readonly LoggerInterface $logger = new NullLogger(),
private readonly NameValidator $nameValidator = new NameValidator(),
private readonly ?LoaderInterface $loader = null,
) {
}
/**
* Runs the configured loader once, on demand. Reads trigger this automatically, so element
* loading is deferred to the first read (request time) rather than eager at build time — under a
* persistent runtime a source not yet ready at build no longer freezes the registry empty.
*
* `loaded` is set only after success, so a transient failure is retried on the next read. The
* `loading` guard lets a loader read the registry during its own run (e.g. discovery's identity
* check) without re-entering the load.
*/
public function load(): void
{
if ($this->loaded || $this->loading || null === $this->loader) {
return;
}
$this->loadFrom($this->loader);
// Only on success: a failure propagates, so it is retried on the next read.
$this->loaded = true;
}
/**
* Runs $loader with the change events its registrations would dispatch suppressed, since they
* describe the registry filling up rather than changing.
*
* Re-entrant-safe, and failure propagates. Does not mark the registry loaded: $loader is the
* caller's, and the one the constructor took is still owed its run.
*/
public function loadFrom(LoaderInterface $loader): void
{
if ($this->loading) {
return;
}
$this->loading = true;
try {
$loader->load($this);
} finally {
$this->loading = false;
}
}
public function registerTool(Tool $tool, callable|array|string $handler): ToolReference
{
if (!$this->nameValidator->isValid($tool->name)) {
$this->logger->warning(
\sprintf('Tool name "%s" is invalid. Tool names should only contain letters (a-z, A-Z), numbers, dots, hyphens, underscores, and forward slashes.', $tool->name),
);
}
$reference = new ToolReference($tool, $handler);
$this->tools[$tool->name] = $reference;
$this->dispatch(new ToolListChangedEvent());
return $reference;
}
public function registerResource(ResourceDefinition $resource, callable|array|string $handler): ResourceReference
{
$reference = new ResourceReference($resource, $handler);
$this->resources[$resource->uri] = $reference;
$this->dispatch(new ResourceListChangedEvent());
return $reference;
}
public function registerResourceTemplate(
ResourceTemplate $template,
callable|array|string $handler,
array $completionProviders = [],
): ResourceTemplateReference {
$reference = new ResourceTemplateReference($template, $handler, $completionProviders);
$this->resourceTemplates[$template->uriTemplate] = $reference;
$this->dispatch(new ResourceTemplateListChangedEvent());
return $reference;
}
public function registerPrompt(
Prompt $prompt,
callable|array|string $handler,
array $completionProviders = [],
): PromptReference {
$reference = new PromptReference($prompt, $handler, $completionProviders);
$this->prompts[$prompt->name] = $reference;
$this->dispatch(new PromptListChangedEvent());
return $reference;
}
public function unregisterTool(string $name): void
{
if (!isset($this->tools[$name])) {
return;
}
unset($this->tools[$name]);
$this->dispatch(new ToolListChangedEvent());
}
public function unregisterResource(string $uri): void
{
if (!isset($this->resources[$uri])) {
return;
}
unset($this->resources[$uri]);
$this->dispatch(new ResourceListChangedEvent());
}
public function unregisterResourceTemplate(string $uriTemplate): void
{
if (!isset($this->resourceTemplates[$uriTemplate])) {
return;
}
unset($this->resourceTemplates[$uriTemplate]);
$this->dispatch(new ResourceTemplateListChangedEvent());
}
public function unregisterPrompt(string $name): void
{
if (!isset($this->prompts[$name])) {
return;
}
unset($this->prompts[$name]);
$this->dispatch(new PromptListChangedEvent());
}
public function hasTool(string $name): bool
{
$this->load();
return isset($this->tools[$name]);
}
public function hasResource(string $uri): bool
{
$this->load();
return isset($this->resources[$uri]);
}
public function hasResourceTemplate(string $uriTemplate): bool
{
$this->load();
return isset($this->resourceTemplates[$uriTemplate]);
}
public function hasPrompt(string $name): bool
{
$this->load();
return isset($this->prompts[$name]);
}
public function hasTools(): bool
{
$this->load();
return [] !== $this->tools;
}
public function getTools(?int $limit = null, ?string $cursor = null): Page
{
$this->load();
$tools = [];
foreach ($this->tools as $toolReference) {
$tools[$toolReference->tool->name] = $toolReference->tool;
}
if (null === $limit) {
return new Page($tools, null);
}
$paginatedTools = $this->paginateResults($tools, $limit, $cursor);
$nextCursor = $this->calculateNextCursor(
\count($tools),
$cursor,
$limit
);
return new Page($paginatedTools, $nextCursor);
}
public function getTool(string $name): ToolReference
{
$this->load();
return $this->tools[$name] ?? throw new ToolNotFoundException($name);
}
public function hasResources(): bool
{
$this->load();
return [] !== $this->resources;
}
public function getResources(?int $limit = null, ?string $cursor = null): Page
{
$this->load();
$resources = [];
foreach ($this->resources as $resourceReference) {
$resources[$resourceReference->resource->uri] = $resourceReference->resource;
}
if (null === $limit) {
return new Page($resources, null);
}
$paginatedResources = $this->paginateResults($resources, $limit, $cursor);
$nextCursor = $this->calculateNextCursor(
\count($resources),
$cursor,
$limit
);
return new Page($paginatedResources, $nextCursor);
}
public function getResource(
string $uri,
bool $includeTemplates = true,
): ResourceReference|ResourceTemplateReference {
$this->load();
$registration = $this->resources[$uri] ?? null;
if ($registration) {
return $registration;
}
if ($includeTemplates) {
foreach ($this->resourceTemplates as $template) {
if ($template->matches($uri)) {
return $template;
}
}
}
$this->logger->debug('No resource matched URI.', ['uri' => $uri]);
throw new ResourceNotFoundException($uri);
}
public function hasResourceTemplates(): bool
{
$this->load();
return [] !== $this->resourceTemplates;
}
public function getResourceTemplates(?int $limit = null, ?string $cursor = null): Page
{
$this->load();
$templates = [];
foreach ($this->resourceTemplates as $templateReference) {
$templates[$templateReference->resourceTemplate->uriTemplate] = $templateReference->resourceTemplate;
}
if (null === $limit) {
return new Page($templates, null);
}
$paginatedTemplates = $this->paginateResults($templates, $limit, $cursor);
$nextCursor = $this->calculateNextCursor(
\count($templates),
$cursor,
$limit
);
return new Page($paginatedTemplates, $nextCursor);
}
public function getResourceTemplate(string $uriTemplate): ResourceTemplateReference
{
$this->load();
return $this->resourceTemplates[$uriTemplate] ?? throw new ResourceNotFoundException($uriTemplate);
}
public function hasPrompts(): bool
{
$this->load();
return [] !== $this->prompts;
}
public function getPrompts(?int $limit = null, ?string $cursor = null): Page
{
$this->load();
$prompts = [];
foreach ($this->prompts as $promptReference) {
$prompts[$promptReference->prompt->name] = $promptReference->prompt;
}
if (null === $limit) {
return new Page($prompts, null);
}
$paginatedPrompts = $this->paginateResults($prompts, $limit, $cursor);
$nextCursor = $this->calculateNextCursor(
\count($prompts),
$cursor,
$limit
);
return new Page($paginatedPrompts, $nextCursor);
}
public function getPrompt(string $name): PromptReference
{
$this->load();
return $this->prompts[$name] ?? throw new PromptNotFoundException($name);
}
/**
* Suppressed while the deferred loader runs, since it only sets up initial state.
*/
private function dispatch(object $event): void
{
if ($this->loading) {
return;
}
$this->eventDispatcher?->dispatch($event);
}
/**
* Calculate next cursor for pagination.
*
* @param int $totalItems Count of all items
* @param string|null $currentCursor Current cursor position
* @param int $limit Number requested/returned per page
*/
private function calculateNextCursor(int $totalItems, ?string $currentCursor, int $limit): ?string
{
$currentOffset = 0;
if (null !== $currentCursor) {
$decodedCursor = base64_decode($currentCursor, true);
if (false !== $decodedCursor && is_numeric($decodedCursor)) {
$currentOffset = (int) $decodedCursor;
}
}
$nextOffset = $currentOffset + $limit;
if ($nextOffset < $totalItems) {
return base64_encode((string) $nextOffset);
}
return null;
}
/**
* Helper method to paginate results using cursor-based pagination.
*
* @param array<int|string, mixed> $items The full array of items to paginate The full array of items to paginate
* @param int $limit Maximum number of items to return
* @param string|null $cursor Base64 encoded offset position
*
* @return array<int|string, mixed> Paginated results
*
* @throws InvalidCursorException When cursor is invalid (MCP error code -32602)
*/
private function paginateResults(array $items, int $limit, ?string $cursor = null): array
{
$offset = 0;
if (null !== $cursor) {
$decodedCursor = base64_decode($cursor, true);
if (false === $decodedCursor || !is_numeric($decodedCursor)) {
throw new InvalidCursorException($cursor);
}
$offset = (int) $decodedCursor;
// Validate offset is within reasonable bounds
if ($offset < 0 || $offset > \count($items)) {
throw new InvalidCursorException($cursor);
}
}
return array_values(\array_slice($items, $offset, $limit));
}
}