|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpMcp\Client\Cache; |
| 6 | + |
| 7 | +use PhpMcp\Client\Exception\DefinitionException; |
| 8 | +use PhpMcp\Client\Model\Definitions\PromptDefinition; |
| 9 | +use PhpMcp\Client\Model\Definitions\ResourceDefinition; |
| 10 | +use PhpMcp\Client\Model\Definitions\ResourceTemplateDefinition; |
| 11 | +use PhpMcp\Client\Model\Definitions\ToolDefinition; |
| 12 | +use Psr\Log\LoggerInterface; |
| 13 | +use Psr\SimpleCache\CacheInterface; |
| 14 | +use Throwable; |
| 15 | + |
| 16 | +/** |
| 17 | + * Handles caching of definitions (tools, resources, prompts) received from servers. |
| 18 | + * Uses a PSR-16 cache implementation provided via ClientConfig. |
| 19 | + * |
| 20 | + * @internal |
| 21 | + */ |
| 22 | +final class DefinitionCache |
| 23 | +{ |
| 24 | + private const CACHE_KEY_PREFIX = 'mcp_client_defs_'; |
| 25 | + |
| 26 | + public function __construct( |
| 27 | + private readonly CacheInterface $cache, |
| 28 | + private readonly int $ttl, // Default TTL in seconds |
| 29 | + private readonly LoggerInterface $logger |
| 30 | + ) {} |
| 31 | + |
| 32 | + /** |
| 33 | + * @return array<ToolDefinition>|null Null if not found or error. |
| 34 | + */ |
| 35 | + public function getTools(string $serverName): ?array |
| 36 | + { |
| 37 | + return $this->get($serverName, 'tools', ToolDefinition::class); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * @param array<ToolDefinition> $tools |
| 42 | + */ |
| 43 | + public function setTools(string $serverName, array $tools): void |
| 44 | + { |
| 45 | + $this->set($serverName, 'tools', $tools); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * @return array<ResourceDefinition>|null |
| 50 | + */ |
| 51 | + public function getResources(string $serverName): ?array |
| 52 | + { |
| 53 | + return $this->get($serverName, 'resources', ResourceDefinition::class); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * @param array<ResourceDefinition> $resources |
| 58 | + */ |
| 59 | + public function setResources(string $serverName, array $resources): void |
| 60 | + { |
| 61 | + $this->set($serverName, 'resources', $resources); |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * @return array<PromptDefinition>|null |
| 66 | + */ |
| 67 | + public function getPrompts(string $serverName): ?array |
| 68 | + { |
| 69 | + return $this->get($serverName, 'prompts', PromptDefinition::class); |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * @param array<PromptDefinition> $prompts |
| 74 | + */ |
| 75 | + public function setPrompts(string $serverName, array $prompts): void |
| 76 | + { |
| 77 | + $this->set($serverName, 'prompts', $prompts); |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * @return array<ResourceTemplateDefinition>|null |
| 82 | + */ |
| 83 | + public function getResourceTemplates(string $serverName): ?array |
| 84 | + { |
| 85 | + return $this->get($serverName, 'res_templates', ResourceTemplateDefinition::class); |
| 86 | + } |
| 87 | + |
| 88 | + /** |
| 89 | + * @param array<ResourceTemplateDefinition> $templates |
| 90 | + */ |
| 91 | + public function setResourceTemplates(string $serverName, array $templates): void |
| 92 | + { |
| 93 | + $this->set($serverName, 'res_templates', $templates); |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Generic get method. |
| 98 | + * |
| 99 | + * @template T of ToolDefinition|ResourceDefinition|PromptDefinition|ResourceTemplateDefinition |
| 100 | + * |
| 101 | + * @param class-string<T> $expectedClass FQCN of the definition class |
| 102 | + * @return array<T>|null |
| 103 | + */ |
| 104 | + private function get(string $serverName, string $type, string $expectedClass): ?array |
| 105 | + { |
| 106 | + $key = $this->generateCacheKey($serverName, $type); |
| 107 | + try { |
| 108 | + $cachedData = $this->cache->get($key); |
| 109 | + |
| 110 | + if ($cachedData === null) { |
| 111 | + return null; // Cache miss |
| 112 | + } |
| 113 | + |
| 114 | + if (! is_array($cachedData)) { |
| 115 | + $this->logger->warning("Invalid data type found in cache for {$key}. Expected array.", ['type' => gettype($cachedData)]); |
| 116 | + $this->cache->delete($key); // Clear invalid cache entry |
| 117 | + |
| 118 | + return null; |
| 119 | + } |
| 120 | + |
| 121 | + $definitions = []; |
| 122 | + foreach ($cachedData as $itemData) { |
| 123 | + if (! is_array($itemData)) { |
| 124 | + $this->logger->warning("Invalid item data type found in cached array for {$key}. Expected array.", ['type' => gettype($itemData)]); |
| 125 | + $this->cache->delete($key); // Clear invalid cache entry |
| 126 | + |
| 127 | + return null; |
| 128 | + } |
| 129 | + // Re-hydrate from array using the static fromArray method |
| 130 | + if (! method_exists($expectedClass, 'fromArray')) { |
| 131 | + throw new DefinitionException("Definition class {$expectedClass} is missing the required fromArray method."); |
| 132 | + } |
| 133 | + |
| 134 | + $definitions[] = call_user_func([$expectedClass, 'fromArray'], $itemData); |
| 135 | + } |
| 136 | + |
| 137 | + return $definitions; |
| 138 | + |
| 139 | + } catch (Throwable $e) { |
| 140 | + // Catch PSR-16 exceptions or hydration errors |
| 141 | + $this->logger->error("Error getting definitions from cache for key '{$key}': {$e->getMessage()}", ['exception' => $e]); |
| 142 | + |
| 143 | + return null; // Return null on error |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + /** |
| 148 | + * Generic set method. |
| 149 | + * |
| 150 | + * @param array<ToolDefinition|ResourceDefinition|PromptDefinition|ResourceTemplateDefinition> $definitions |
| 151 | + */ |
| 152 | + private function set(string $serverName, string $type, array $definitions): void |
| 153 | + { |
| 154 | + $key = $this->generateCacheKey($serverName, $type); |
| 155 | + try { |
| 156 | + // Convert definition objects back to arrays for caching |
| 157 | + $dataToCache = array_map(function ($definition) { |
| 158 | + if (! method_exists($definition, 'toArray')) { |
| 159 | + throw new DefinitionException('Definition class '.get_class($definition).' is missing the required toArray method for caching.'); |
| 160 | + } |
| 161 | + |
| 162 | + return $definition->toArray(); // Assuming a toArray exists for caching |
| 163 | + }, $definitions); |
| 164 | + |
| 165 | + $this->cache->set($key, $dataToCache, $this->ttl); |
| 166 | + } catch (Throwable $e) { |
| 167 | + // Catch PSR-16 exceptions or serialization errors |
| 168 | + $this->logger->error("Error setting definitions to cache for key '{$key}': {$e->getMessage()}", ['exception' => $e]); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + private function generateCacheKey(string $serverName, string $type): string |
| 173 | + { |
| 174 | + // Sanitize server name for cache key safety |
| 175 | + $safeServerName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $serverName); |
| 176 | + |
| 177 | + return self::CACHE_KEY_PREFIX.$safeServerName.'_'.$type; |
| 178 | + } |
| 179 | + |
| 180 | + /** Invalidate cache for a specific server */ |
| 181 | + public function invalidateServerCache(string $serverName): void |
| 182 | + { |
| 183 | + $keys = [ |
| 184 | + $this->generateCacheKey($serverName, 'tools'), |
| 185 | + $this->generateCacheKey($serverName, 'resources'), |
| 186 | + $this->generateCacheKey($serverName, 'prompts'), |
| 187 | + $this->generateCacheKey($serverName, 'res_templates'), |
| 188 | + ]; |
| 189 | + try { |
| 190 | + $this->cache->deleteMultiple($keys); |
| 191 | + $this->logger->info("Invalidated definition cache for server '{$serverName}'."); |
| 192 | + } catch (Throwable $e) { |
| 193 | + $this->logger->error("Error invalidating cache for server '{$serverName}': {$e->getMessage()}", ['exception' => $e]); |
| 194 | + } |
| 195 | + } |
| 196 | +} |
0 commit comments