1: <?php
2:
3: declare(strict_types=1);
4:
5: /**
6: * This file is part of the Nexus MCP SDK package.
7: *
8: * (c) 2026 John Paul E. Balandan, CPA <paulbalandan@gmail.com>
9: *
10: * For the full copyright and license information, please view
11: * the LICENSE file that was distributed with this source code.
12: */
13:
14: namespace Nexus\Mcp\Server\Resource;
15:
16: use Nexus\Mcp\Core\Schema\Cursor;
17: use Nexus\Mcp\Core\Schema\Result\InputRequiredResult;
18: use Nexus\Mcp\Core\Schema\Result\ListResourcesResult;
19: use Nexus\Mcp\Core\Schema\Result\ReadResourceResult;
20: use Nexus\Mcp\Server\Exception\ResourceNotFoundException;
21: use Nexus\Mcp\Server\ListChangeSourceInterface;
22: use Nexus\Mcp\Server\ServerContext;
23:
24: /**
25: * Chains a primary `ResourceStoreInterface` (exact-URI matches) with a fallback
26: * `ResourceTemplateStoreInterface` (URI-template matches). `read()` tries the
27: * primary first. On `ResourceNotFoundException` it falls through to the template
28: * store, only re-raising the not-found when neither side matches. `list()`
29: * delegates to the primary unchanged.
30: */
31: final readonly class CompositeResourceStore implements ListChangeSourceInterface, ResourceStoreInterface
32: {
33: public function __construct(private ResourceStoreInterface $resourceStore, private ResourceTemplateStoreInterface $resourceTemplateStore)
34: {
35: }
36:
37: #[\Override]
38: public function onListChanged(\Closure $listener): void
39: {
40: foreach ([$this->resourceStore, $this->resourceTemplateStore] as $store) {
41: if ($store instanceof ListChangeSourceInterface) {
42: $store->onListChanged($listener);
43: }
44: }
45: }
46:
47: #[\Override]
48: public function list(?Cursor $cursor): ListResourcesResult
49: {
50: return $this->resourceStore->list($cursor);
51: }
52:
53: #[\Override]
54: public function read(string $uri, ServerContext $context): InputRequiredResult|ReadResourceResult
55: {
56: try {
57: return $this->resourceStore->read($uri, $context);
58: } catch (ResourceNotFoundException) {
59: return $this->resourceTemplateStore->read($uri, $context);
60: }
61: }
62: }
63: