{"repo_name": "server", "file_name": "/server/src/Elements/RegisteredResource.php", "inference_info": {"prefix_code": " Array of ResourceContents objects.\n */\n public function read(ContainerInterface $container, string $uri, Context $context): array\n {\n $result = $this->handle($container, ['uri' => $uri], $context);\n\n return $this->formatResult($result, $uri, $this->schema->mimeType);\n }\n\n /**\n * Formats the raw result of a resource read operation into MCP ResourceContent items.\n *\n * @param mixed $readResult The raw result from the resource handler method.\n * @param string $uri The URI of the resource that was read.\n * @param ?string $mimeType The MIME type from the ResourceDefinition.\n * @return array Array of ResourceContents objects.\n *\n * @throws \\RuntimeException If the result cannot be formatted.\n *\n * Supported result types:\n * - ResourceContent: Used as-is\n * - EmbeddedResource: Resource is extracted from the EmbeddedResource\n * - string: Converted to text content with guessed or provided MIME type\n * - stream resource: Read and converted to blob with provided MIME type\n * - array with 'blob' key: Used as blob content\n * - array with 'text' key: Used as text content\n * - SplFileInfo: Read and converted to blob\n * - array: Converted to JSON if MIME type is application/json or contains 'json'\n * For other MIME types, will try to convert to JSON with a warning\n */\n protected function formatResult(mixed $readResult, string $uri, ?string $mimeType): array\n {\n if ($readResult instanceof ResourceContents) {\n return [$readResult];\n }\n\n if ($readResult instanceof EmbeddedResource) {\n return [$readResult->resource];\n }\n\n if (is_array($readResult)) {\n if (empty($readResult)) {\n return [TextResourceContents::make($uri, 'application/json', '[]')];\n }\n\n $allAreResourceContents = true;\n $hasResourceContents = false;\n $allAreEmbeddedResource = true;\n $hasEmbeddedResource = false;\n\n foreach ($readResult as $item) {\n if ($item instanceof ResourceContents) {\n $hasResourceContents = true;\n $allAreEmbeddedResource = false;\n } elseif ($item instanceof EmbeddedResource) {\n $hasEmbeddedResource = true;\n $allAreResourceContents = false;\n } else {\n $allAreResourceContents = false;\n $allAreEmbeddedResource = false;\n }\n }\n\n if ($allAreResourceContents && $hasResourceContents) {\n return $readResult;\n }\n\n if ($allAreEmbeddedResource && $hasEmbeddedResource) {\n return array_map(fn($item) => $item->resource, $readResult);\n }\n\n ", "suffix_code": "\n }\n\n if (is_string($readResult)) {\n $mimeType = $mimeType ?? $this->guessMimeTypeFromString($readResult);\n\n return [TextResourceContents::make($uri, $mimeType, $readResult)];\n }\n\n if (is_resource($readResult) && get_resource_type($readResult) === 'stream') {\n $result = BlobResourceContents::fromStream(\n $uri,\n $readResult,\n $mimeType ?? 'application/octet-stream'\n );\n\n @fclose($readResult);\n\n return [$result];\n }\n\n if (is_array($readResult) && isset($readResult['blob']) && is_string($readResult['blob'])) {\n $mimeType = $readResult['mimeType'] ?? $mimeType ?? 'application/octet-stream';\n\n return [BlobResourceContents::make($uri, $mimeType, $readResult['blob'])];\n }\n\n if (is_array($readResult) && isset($readResult['text']) && is_string($readResult['text'])) {\n $mimeType = $readResult['mimeType'] ?? $mimeType ?? 'text/plain';\n\n return [TextResourceContents::make($uri, $mimeType, $readResult['text'])];\n }\n\n if ($readResult instanceof \\SplFileInfo && $readResult->isFile() && $readResult->isReadable()) {\n if ($mimeType && str_contains(strtolower($mimeType), 'text')) {\n return [TextResourceContents::make($uri, $mimeType, file_get_contents($readResult->getPathname()))];\n }\n\n return [BlobResourceContents::fromSplFileInfo($uri, $readResult, $mimeType)];\n }\n\n if (is_array($readResult)) {\n if ($mimeType && (str_contains(strtolower($mimeType), 'json') ||\n $mimeType === 'application/json')) {\n try {\n $jsonString = json_encode($readResult, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);\n\n return [TextResourceContents::make($uri, $mimeType, $jsonString)];\n } catch (\\JsonException $e) {\n throw new \\RuntimeException(\"Failed to encode array as JSON for URI '{$uri}': {$e->getMessage()}\");\n }\n }\n\n try {\n $jsonString = json_encode($readResult, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);\n $mimeType = $mimeType ?? 'application/json';\n\n return [TextResourceContents::make($uri, $mimeType, $jsonString)];\n } catch (\\JsonException $e) {\n throw new \\RuntimeException(\"Failed to encode array as JSON for URI '{$uri}': {$e->getMessage()}\");\n }\n }\n\n throw new \\RuntimeException(\"Cannot format resource read result for URI '{$uri}'. Handler method returned unhandled type: \" . gettype($readResult));\n }\n\n /** Guesses MIME type from string content (very basic) */\n private function guessMimeTypeFromString(string $content): string\n {\n $trimmed = ltrim($content);\n\n if (str_starts_with($trimmed, '<') && str_ends_with(rtrim($content), '>')) {\n if (str_contains($trimmed, ' $this->schema->toArray(),\n ...parent::toArray(),\n ];\n }\n\n public static function fromArray(array $data): self|false\n {\n try {\n if (! isset($data['schema']) || ! isset($data['handler'])) {\n return false;\n }\n\n return new self(\n Resource::fromArray($data['schema']),\n $data['handler'],\n $data['isManual'] ?? false,\n );\n } catch (Throwable $e) {\n return false;\n }\n }\n}\n", "middle_code": "if ($hasResourceContents || $hasEmbeddedResource) {\n $result = [];\n foreach ($readResult as $item) {\n if ($item instanceof ResourceContents) {\n $result[] = $item;\n } elseif ($item instanceof EmbeddedResource) {\n $result[] = $item->resource;\n } else {\n $result = array_merge($result, $this->formatResult($item, $uri, $mimeType));\n }\n }\n return $result;\n }", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "php", "sub_task_type": "if_statement"}, "context_code": [["/server/src/Elements/RegisteredResourceTemplate.php", "compileTemplate();\n }\n\n public static function make(ResourceTemplate $schema, callable|array|string $handler, bool $isManual = false, array $completionProviders = []): self\n {\n return new self($schema, $handler, $isManual, $completionProviders);\n }\n\n /**\n * Gets the resource template.\n *\n * @return array Array of ResourceContents objects.\n */\n public function read(ContainerInterface $container, string $uri, Context $context): array\n {\n $arguments = array_merge($this->uriVariables, ['uri' => $uri]);\n\n $result = $this->handle($container, $arguments, $context);\n\n return $this->formatResult($result, $uri, $this->schema->mimeType);\n }\n\n public function complete(ContainerInterface $container, string $argument, string $value, SessionInterface $session): CompletionCompleteResult\n {\n $providerClassOrInstance = $this->completionProviders[$argument] ?? null;\n if ($providerClassOrInstance === null) {\n return new CompletionCompleteResult([]);\n }\n\n if (is_string($providerClassOrInstance)) {\n if (! class_exists($providerClassOrInstance)) {\n throw new \\RuntimeException(\"Completion provider class '{$providerClassOrInstance}' does not exist.\");\n }\n\n $provider = $container->get($providerClassOrInstance);\n } else {\n $provider = $providerClassOrInstance;\n }\n\n $completions = $provider->getCompletions($value, $session);\n\n $total = count($completions);\n $hasMore = $total > 100;\n\n $pagedCompletions = array_slice($completions, 0, 100);\n\n return new CompletionCompleteResult($pagedCompletions, $total, $hasMore);\n }\n\n\n public function getVariableNames(): array\n {\n return $this->variableNames;\n }\n\n public function matches(string $uri): bool\n {\n if (preg_match($this->uriTemplateRegex, $uri, $matches)) {\n $variables = [];\n foreach ($this->variableNames as $varName) {\n if (isset($matches[$varName])) {\n $variables[$varName] = $matches[$varName];\n }\n }\n\n $this->uriVariables = $variables;\n\n return true;\n }\n\n return false;\n }\n\n private function compileTemplate(): void\n {\n $this->variableNames = [];\n $regexParts = [];\n\n $segments = preg_split('/(\\{\\w+\\})/', $this->schema->uriTemplate, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);\n\n foreach ($segments as $segment) {\n if (preg_match('/^\\{(\\w+)\\}$/', $segment, $matches)) {\n $varName = $matches[1];\n $this->variableNames[] = $varName;\n $regexParts[] = '(?P<' . $varName . '>[^/]+)';\n } else {\n $regexParts[] = preg_quote($segment, '#');\n }\n }\n\n $this->uriTemplateRegex = '#^' . implode('', $regexParts) . '$#';\n }\n\n /**\n * Formats the raw result of a resource read operation into MCP ResourceContent items.\n *\n * @param mixed $readResult The raw result from the resource handler method.\n * @param string $uri The URI of the resource that was read.\n * @param ?string $defaultMimeType The default MIME type from the ResourceDefinition.\n * @return array Array of ResourceContents objects.\n *\n * @throws \\RuntimeException If the result cannot be formatted.\n *\n * Supported result types:\n * - ResourceContent: Used as-is\n * - EmbeddedResource: Resource is extracted from the EmbeddedResource\n * - string: Converted to text content with guessed or provided MIME type\n * - stream resource: Read and converted to blob with provided MIME type\n * - array with 'blob' key: Used as blob content\n * - array with 'text' key: Used as text content\n * - SplFileInfo: Read and converted to blob\n * - array: Converted to JSON if MIME type is application/json or contains 'json'\n * For other MIME types, will try to convert to JSON with a warning\n */\n protected function formatResult(mixed $readResult, string $uri, ?string $mimeType): array\n {\n if ($readResult instanceof ResourceContents) {\n return [$readResult];\n }\n\n if ($readResult instanceof EmbeddedResource) {\n return [$readResult->resource];\n }\n\n if (is_array($readResult)) {\n if (empty($readResult)) {\n return [TextResourceContents::make($uri, 'application/json', '[]')];\n }\n\n $allAreResourceContents = true;\n $hasResourceContents = false;\n $allAreEmbeddedResource = true;\n $hasEmbeddedResource = false;\n\n foreach ($readResult as $item) {\n if ($item instanceof ResourceContents) {\n $hasResourceContents = true;\n $allAreEmbeddedResource = false;\n } elseif ($item instanceof EmbeddedResource) {\n $hasEmbeddedResource = true;\n $allAreResourceContents = false;\n } else {\n $allAreResourceContents = false;\n $allAreEmbeddedResource = false;\n }\n }\n\n if ($allAreResourceContents && $hasResourceContents) {\n return $readResult;\n }\n\n if ($allAreEmbeddedResource && $hasEmbeddedResource) {\n return array_map(fn($item) => $item->resource, $readResult);\n }\n\n if ($hasResourceContents || $hasEmbeddedResource) {\n $result = [];\n foreach ($readResult as $item) {\n if ($item instanceof ResourceContents) {\n $result[] = $item;\n } elseif ($item instanceof EmbeddedResource) {\n $result[] = $item->resource;\n } else {\n $result = array_merge($result, $this->formatResult($item, $uri, $mimeType));\n }\n }\n return $result;\n }\n }\n\n if (is_string($readResult)) {\n $mimeType = $mimeType ?? $this->guessMimeTypeFromString($readResult);\n\n return [TextResourceContents::make($uri, $mimeType, $readResult)];\n }\n\n if (is_resource($readResult) && get_resource_type($readResult) === 'stream') {\n $result = BlobResourceContents::fromStream(\n $uri,\n $readResult,\n $mimeType ?? 'application/octet-stream'\n );\n\n @fclose($readResult);\n\n return [$result];\n }\n\n if (is_array($readResult) && isset($readResult['blob']) && is_string($readResult['blob'])) {\n $mimeType = $readResult['mimeType'] ?? $mimeType ?? 'application/octet-stream';\n\n return [BlobResourceContents::make($uri, $mimeType, $readResult['blob'])];\n }\n\n if (is_array($readResult) && isset($readResult['text']) && is_string($readResult['text'])) {\n $mimeType = $readResult['mimeType'] ?? $mimeType ?? 'text/plain';\n\n return [TextResourceContents::make($uri, $mimeType, $readResult['text'])];\n }\n\n if ($readResult instanceof \\SplFileInfo && $readResult->isFile() && $readResult->isReadable()) {\n if ($mimeType && str_contains(strtolower($mimeType), 'text')) {\n return [TextResourceContents::make($uri, $mimeType, file_get_contents($readResult->getPathname()))];\n }\n\n return [BlobResourceContents::fromSplFileInfo($uri, $readResult, $mimeType)];\n }\n\n if (is_array($readResult)) {\n if ($mimeType && (str_contains(strtolower($mimeType), 'json') ||\n $mimeType === 'application/json')) {\n try {\n $jsonString = json_encode($readResult, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);\n\n return [TextResourceContents::make($uri, $mimeType, $jsonString)];\n } catch (\\JsonException $e) {\n throw new \\RuntimeException(\"Failed to encode array as JSON for URI '{$uri}': {$e->getMessage()}\");\n }\n }\n\n try {\n $jsonString = json_encode($readResult, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);\n $mimeType = $mimeType ?? 'application/json';\n\n return [TextResourceContents::make($uri, $mimeType, $jsonString)];\n } catch (\\JsonException $e) {\n throw new \\RuntimeException(\"Failed to encode array as JSON for URI '{$uri}': {$e->getMessage()}\");\n }\n }\n\n throw new \\RuntimeException(\"Cannot format resource read result for URI '{$uri}'. Handler method returned unhandled type: \" . gettype($readResult));\n }\n\n /** Guesses MIME type from string content (very basic) */\n private function guessMimeTypeFromString(string $content): string\n {\n $trimmed = ltrim($content);\n\n if (str_starts_with($trimmed, '<') && str_ends_with(rtrim($content), '>')) {\n if (str_contains($trimmed, 'completionProviders as $argument => $provider) {\n $completionProviders[$argument] = serialize($provider);\n }\n\n return [\n 'schema' => $this->schema->toArray(),\n 'completionProviders' => $completionProviders,\n ...parent::toArray(),\n ];\n }\n\n public static function fromArray(array $data): self|false\n {\n try {\n if (! isset($data['schema']) || ! isset($data['handler'])) {\n return false;\n }\n\n $completionProviders = [];\n foreach ($data['completionProviders'] ?? [] as $argument => $provider) {\n $completionProviders[$argument] = unserialize($provider);\n }\n\n return new self(\n ResourceTemplate::fromArray($data['schema']),\n $data['handler'],\n $data['isManual'] ?? false,\n $completionProviders,\n );\n } catch (Throwable $e) {\n return false;\n }\n }\n}\n"], ["/server/src/Elements/RegisteredPrompt.php", "handle($container, $arguments, $context);\n\n return $this->formatResult($result);\n }\n\n public function complete(ContainerInterface $container, string $argument, string $value, SessionInterface $session): CompletionCompleteResult\n {\n $providerClassOrInstance = $this->completionProviders[$argument] ?? null;\n if ($providerClassOrInstance === null) {\n return new CompletionCompleteResult([]);\n }\n\n if (is_string($providerClassOrInstance)) {\n if (! class_exists($providerClassOrInstance)) {\n throw new \\RuntimeException(\"Completion provider class '{$providerClassOrInstance}' does not exist.\");\n }\n\n $provider = $container->get($providerClassOrInstance);\n } else {\n $provider = $providerClassOrInstance;\n }\n\n $completions = $provider->getCompletions($value, $session);\n\n $total = count($completions);\n $hasMore = $total > 100;\n\n $pagedCompletions = array_slice($completions, 0, 100);\n\n return new CompletionCompleteResult($pagedCompletions, $total, $hasMore);\n }\n\n /**\n * Formats the raw result of a prompt generator into an array of MCP PromptMessages.\n *\n * @param mixed $promptGenerationResult Expected: array of message structures.\n * @return PromptMessage[] Array of PromptMessage objects.\n *\n * @throws \\RuntimeException If the result cannot be formatted.\n * @throws \\JsonException If JSON encoding fails.\n */\n protected function formatResult(mixed $promptGenerationResult): array\n {\n if ($promptGenerationResult instanceof PromptMessage) {\n return [$promptGenerationResult];\n }\n\n if (! is_array($promptGenerationResult)) {\n throw new \\RuntimeException('Prompt generator method must return an array of messages.');\n }\n\n if (empty($promptGenerationResult)) {\n return [];\n }\n\n if (is_array($promptGenerationResult)) {\n $allArePromptMessages = true;\n $hasPromptMessages = false;\n\n foreach ($promptGenerationResult as $item) {\n if ($item instanceof PromptMessage) {\n $hasPromptMessages = true;\n } else {\n $allArePromptMessages = false;\n }\n }\n\n if ($allArePromptMessages && $hasPromptMessages) {\n return $promptGenerationResult;\n }\n\n if ($hasPromptMessages) {\n $result = [];\n foreach ($promptGenerationResult as $index => $item) {\n if ($item instanceof PromptMessage) {\n $result[] = $item;\n } else {\n $result = array_merge($result, $this->formatResult($item));\n }\n }\n return $result;\n }\n\n if (! array_is_list($promptGenerationResult)) {\n if (isset($promptGenerationResult['user']) || isset($promptGenerationResult['assistant'])) {\n $result = [];\n if (isset($promptGenerationResult['user'])) {\n $userContent = $this->formatContent($promptGenerationResult['user']);\n $result[] = PromptMessage::make(Role::User, $userContent);\n }\n if (isset($promptGenerationResult['assistant'])) {\n $assistantContent = $this->formatContent($promptGenerationResult['assistant']);\n $result[] = PromptMessage::make(Role::Assistant, $assistantContent);\n }\n return $result;\n }\n\n if (isset($promptGenerationResult['role']) && isset($promptGenerationResult['content'])) {\n return [$this->formatMessage($promptGenerationResult)];\n }\n\n throw new \\RuntimeException('Associative array must contain either role/content keys or user/assistant keys.');\n }\n\n $formattedMessages = [];\n foreach ($promptGenerationResult as $index => $message) {\n if ($message instanceof PromptMessage) {\n $formattedMessages[] = $message;\n } else {\n $formattedMessages[] = $this->formatMessage($message, $index);\n }\n }\n return $formattedMessages;\n }\n\n throw new \\RuntimeException('Invalid prompt generation result format.');\n }\n\n /**\n * Formats a single message into a PromptMessage.\n */\n private function formatMessage(mixed $message, ?int $index = null): PromptMessage\n {\n $indexStr = $index !== null ? \" at index {$index}\" : '';\n\n if (! is_array($message) || ! array_key_exists('role', $message) || ! array_key_exists('content', $message)) {\n throw new \\RuntimeException(\"Invalid message format{$indexStr}. Expected an array with 'role' and 'content' keys.\");\n }\n\n $role = $message['role'] instanceof Role ? $message['role'] : Role::tryFrom($message['role']);\n if ($role === null) {\n throw new \\RuntimeException(\"Invalid role '{$message['role']}' in prompt message{$indexStr}. Only 'user' or 'assistant' are supported.\");\n }\n\n $content = $this->formatContent($message['content'], $index);\n\n return new PromptMessage($role, $content);\n }\n\n /**\n * Formats content into a proper Content object.\n */\n private function formatContent(mixed $content, ?int $index = null): TextContent|ImageContent|AudioContent|EmbeddedResource\n {\n $indexStr = $index !== null ? \" at index {$index}\" : '';\n\n if ($content instanceof Content) {\n if (\n $content instanceof TextContent || $content instanceof ImageContent ||\n $content instanceof AudioContent || $content instanceof EmbeddedResource\n ) {\n return $content;\n }\n throw new \\RuntimeException(\"Invalid Content type{$indexStr}. PromptMessage only supports TextContent, ImageContent, AudioContent, or EmbeddedResource.\");\n }\n\n if (is_string($content)) {\n return TextContent::make($content);\n }\n\n if (is_array($content) && isset($content['type'])) {\n return $this->formatTypedContent($content, $index);\n }\n\n if (is_scalar($content) || $content === null) {\n $stringContent = $content === null ? '(null)' : (is_bool($content) ? ($content ? 'true' : 'false') : (string)$content);\n return TextContent::make($stringContent);\n }\n\n $jsonContent = json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);\n return TextContent::make($jsonContent);\n }\n\n /**\n * Formats typed content arrays into Content objects.\n */\n private function formatTypedContent(array $content, ?int $index = null): TextContent|ImageContent|AudioContent|EmbeddedResource\n {\n $indexStr = $index !== null ? \" at index {$index}\" : '';\n $type = $content['type'];\n\n return match ($type) {\n 'text' => $this->formatTextContent($content, $indexStr),\n 'image' => $this->formatImageContent($content, $indexStr),\n 'audio' => $this->formatAudioContent($content, $indexStr),\n 'resource' => $this->formatResourceContent($content, $indexStr),\n default => throw new \\RuntimeException(\"Invalid content type '{$type}'{$indexStr}.\")\n };\n }\n\n private function formatTextContent(array $content, string $indexStr): TextContent\n {\n if (! isset($content['text']) || ! is_string($content['text'])) {\n throw new \\RuntimeException(\"Invalid 'text' content{$indexStr}: Missing or invalid 'text' string.\");\n }\n return TextContent::make($content['text']);\n }\n\n private function formatImageContent(array $content, string $indexStr): ImageContent\n {\n if (! isset($content['data']) || ! is_string($content['data'])) {\n throw new \\RuntimeException(\"Invalid 'image' content{$indexStr}: Missing or invalid 'data' string (base64).\");\n }\n if (! isset($content['mimeType']) || ! is_string($content['mimeType'])) {\n throw new \\RuntimeException(\"Invalid 'image' content{$indexStr}: Missing or invalid 'mimeType' string.\");\n }\n return ImageContent::make($content['data'], $content['mimeType']);\n }\n\n private function formatAudioContent(array $content, string $indexStr): AudioContent\n {\n if (! isset($content['data']) || ! is_string($content['data'])) {\n throw new \\RuntimeException(\"Invalid 'audio' content{$indexStr}: Missing or invalid 'data' string (base64).\");\n }\n if (! isset($content['mimeType']) || ! is_string($content['mimeType'])) {\n throw new \\RuntimeException(\"Invalid 'audio' content{$indexStr}: Missing or invalid 'mimeType' string.\");\n }\n return AudioContent::make($content['data'], $content['mimeType']);\n }\n\n private function formatResourceContent(array $content, string $indexStr): EmbeddedResource\n {\n if (! isset($content['resource']) || ! is_array($content['resource'])) {\n throw new \\RuntimeException(\"Invalid 'resource' content{$indexStr}: Missing or invalid 'resource' object.\");\n }\n\n $resource = $content['resource'];\n if (! isset($resource['uri']) || ! is_string($resource['uri'])) {\n throw new \\RuntimeException(\"Invalid resource{$indexStr}: Missing or invalid 'uri'.\");\n }\n\n if (isset($resource['text']) && is_string($resource['text'])) {\n $resourceObj = TextResourceContents::make($resource['uri'], $resource['mimeType'] ?? 'text/plain', $resource['text']);\n } elseif (isset($resource['blob']) && is_string($resource['blob'])) {\n $resourceObj = BlobResourceContents::make(\n $resource['uri'],\n $resource['mimeType'] ?? 'application/octet-stream',\n $resource['blob']\n );\n } else {\n throw new \\RuntimeException(\"Invalid resource{$indexStr}: Must contain 'text' or 'blob'.\");\n }\n\n return new EmbeddedResource($resourceObj);\n }\n\n public function toArray(): array\n {\n $completionProviders = [];\n foreach ($this->completionProviders as $argument => $provider) {\n $completionProviders[$argument] = serialize($provider);\n }\n\n return [\n 'schema' => $this->schema->toArray(),\n 'completionProviders' => $completionProviders,\n ...parent::toArray(),\n ];\n }\n\n public static function fromArray(array $data): self|false\n {\n try {\n if (! isset($data['schema']) || ! isset($data['handler'])) {\n return false;\n }\n\n $completionProviders = [];\n foreach ($data['completionProviders'] ?? [] as $argument => $provider) {\n $completionProviders[$argument] = unserialize($provider);\n }\n\n return new self(\n Prompt::fromArray($data['schema']),\n $data['handler'],\n $data['isManual'] ?? false,\n $completionProviders,\n );\n } catch (Throwable $e) {\n return false;\n }\n }\n}\n"], ["/server/src/Elements/RegisteredTool.php", "handle($container, $arguments, $context);\n\n return $this->formatResult($result);\n }\n\n /**\n * Formats the result of a tool execution into an array of MCP Content items.\n *\n * - If the result is already a Content object, it's wrapped in an array.\n * - If the result is an array:\n * - If all elements are Content objects, the array is returned as is.\n * - If it's a mixed array (Content and non-Content items), non-Content items are\n * individually formatted (scalars to TextContent, others to JSON TextContent).\n * - If it's an array with no Content items, the entire array is JSON-encoded into a single TextContent.\n * - Scalars (string, int, float, bool) are wrapped in TextContent.\n * - null is represented as TextContent('(null)').\n * - Other objects are JSON-encoded and wrapped in TextContent.\n *\n * @param mixed $toolExecutionResult The raw value returned by the tool's PHP method.\n * @return Content[] The content items for CallToolResult.\n * @throws JsonException if JSON encoding fails for non-Content array/object results.\n */\n protected function formatResult(mixed $toolExecutionResult): array\n {\n if ($toolExecutionResult instanceof Content) {\n return [$toolExecutionResult];\n }\n\n if (is_array($toolExecutionResult)) {\n if (empty($toolExecutionResult)) {\n return [TextContent::make('[]')];\n }\n\n $allAreContent = true;\n $hasContent = false;\n\n foreach ($toolExecutionResult as $item) {\n if ($item instanceof Content) {\n $hasContent = true;\n } else {\n $allAreContent = false;\n }\n }\n\n if ($allAreContent && $hasContent) {\n return $toolExecutionResult;\n }\n\n if ($hasContent) {\n $result = [];\n foreach ($toolExecutionResult as $item) {\n if ($item instanceof Content) {\n $result[] = $item;\n } else {\n $result = array_merge($result, $this->formatResult($item));\n }\n }\n return $result;\n }\n }\n\n if ($toolExecutionResult === null) {\n return [TextContent::make('(null)')];\n }\n\n if (is_bool($toolExecutionResult)) {\n return [TextContent::make($toolExecutionResult ? 'true' : 'false')];\n }\n\n if (is_scalar($toolExecutionResult)) {\n return [TextContent::make($toolExecutionResult)];\n }\n\n $jsonResult = json_encode(\n $toolExecutionResult,\n JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE\n );\n\n return [TextContent::make($jsonResult)];\n }\n\n public function toArray(): array\n {\n return [\n 'schema' => $this->schema->toArray(),\n ...parent::toArray(),\n ];\n }\n\n public static function fromArray(array $data): self|false\n {\n try {\n if (! isset($data['schema']) || ! isset($data['handler'])) {\n return false;\n }\n\n return new self(\n Tool::fromArray($data['schema']),\n $data['handler'],\n $data['isManual'] ?? false,\n );\n } catch (Throwable $e) {\n return false;\n }\n }\n}\n"], ["/server/src/Dispatcher.php", "container = $this->configuration->container;\n $this->logger = $this->configuration->logger;\n\n $this->schemaValidator ??= new SchemaValidator($this->logger);\n }\n\n public function handleRequest(Request $request, Context $context): Result\n {\n switch ($request->method) {\n case 'initialize':\n $request = InitializeRequest::fromRequest($request);\n return $this->handleInitialize($request, $context->session);\n case 'ping':\n $request = PingRequest::fromRequest($request);\n return $this->handlePing($request);\n case 'tools/list':\n $request = ListToolsRequest::fromRequest($request);\n return $this->handleToolList($request);\n case 'tools/call':\n $request = CallToolRequest::fromRequest($request);\n return $this->handleToolCall($request, $context);\n case 'resources/list':\n $request = ListResourcesRequest::fromRequest($request);\n return $this->handleResourcesList($request);\n case 'resources/templates/list':\n $request = ListResourceTemplatesRequest::fromRequest($request);\n return $this->handleResourceTemplateList($request);\n case 'resources/read':\n $request = ReadResourceRequest::fromRequest($request);\n return $this->handleResourceRead($request, $context);\n case 'resources/subscribe':\n $request = ResourceSubscribeRequest::fromRequest($request);\n return $this->handleResourceSubscribe($request, $context->session);\n case 'resources/unsubscribe':\n $request = ResourceUnsubscribeRequest::fromRequest($request);\n return $this->handleResourceUnsubscribe($request, $context->session);\n case 'prompts/list':\n $request = ListPromptsRequest::fromRequest($request);\n return $this->handlePromptsList($request);\n case 'prompts/get':\n $request = GetPromptRequest::fromRequest($request);\n return $this->handlePromptGet($request, $context);\n case 'logging/setLevel':\n $request = SetLogLevelRequest::fromRequest($request);\n return $this->handleLoggingSetLevel($request, $context->session);\n case 'completion/complete':\n $request = CompletionCompleteRequest::fromRequest($request);\n return $this->handleCompletionComplete($request, $context->session);\n default:\n throw McpServerException::methodNotFound(\"Method '{$request->method}' not found.\");\n }\n }\n\n public function handleNotification(Notification $notification, SessionInterface $session): void\n {\n switch ($notification->method) {\n case 'notifications/initialized':\n $notification = InitializedNotification::fromNotification($notification);\n $this->handleNotificationInitialized($notification, $session);\n }\n }\n\n public function handleInitialize(InitializeRequest $request, SessionInterface $session): InitializeResult\n {\n if (in_array($request->protocolVersion, Protocol::SUPPORTED_PROTOCOL_VERSIONS)) {\n $protocolVersion = $request->protocolVersion;\n } else {\n $protocolVersion = Protocol::LATEST_PROTOCOL_VERSION;\n }\n\n $session->set('client_info', $request->clientInfo->toArray());\n $session->set('protocol_version', $protocolVersion);\n\n $serverInfo = $this->configuration->serverInfo;\n $capabilities = $this->configuration->capabilities;\n $instructions = $this->configuration->instructions;\n\n return new InitializeResult($protocolVersion, $capabilities, $serverInfo, $instructions);\n }\n\n public function handlePing(PingRequest $request): EmptyResult\n {\n return new EmptyResult();\n }\n\n public function handleToolList(ListToolsRequest $request): ListToolsResult\n {\n $limit = $this->configuration->paginationLimit;\n $offset = $this->decodeCursor($request->cursor);\n $allItems = $this->registry->getTools();\n $pagedItems = array_slice($allItems, $offset, $limit);\n $nextCursor = $this->encodeNextCursor($offset, count($pagedItems), count($allItems), $limit);\n\n return new ListToolsResult(array_values($pagedItems), $nextCursor);\n }\n\n public function handleToolCall(CallToolRequest $request, Context $context): CallToolResult\n {\n $toolName = $request->name;\n $arguments = $request->arguments;\n\n $registeredTool = $this->registry->getTool($toolName);\n if (! $registeredTool) {\n throw McpServerException::methodNotFound(\"Tool '{$toolName}' not found.\");\n }\n\n $inputSchema = $registeredTool->schema->inputSchema;\n\n $validationErrors = $this->schemaValidator->validateAgainstJsonSchema($arguments, $inputSchema);\n\n if (! empty($validationErrors)) {\n $errorMessages = [];\n\n foreach ($validationErrors as $errorDetail) {\n $pointer = $errorDetail['pointer'] ?? '';\n $message = $errorDetail['message'] ?? 'Unknown validation error';\n $errorMessages[] = ($pointer !== '/' && $pointer !== '' ? \"Property '{$pointer}': \" : '') . $message;\n }\n\n $summaryMessage = \"Invalid parameters for tool '{$toolName}': \" . implode('; ', array_slice($errorMessages, 0, 3));\n\n if (count($errorMessages) > 3) {\n $summaryMessage .= '; ...and more errors.';\n }\n\n throw McpServerException::invalidParams($summaryMessage, data: ['validation_errors' => $validationErrors]);\n }\n\n try {\n $result = $registeredTool->call($this->container, $arguments, $context);\n\n return new CallToolResult($result, false);\n } catch (JsonException $e) {\n $this->logger->warning('Failed to JSON encode tool result.', ['tool' => $toolName, 'exception' => $e]);\n $errorMessage = \"Failed to serialize tool result: {$e->getMessage()}\";\n\n return new CallToolResult([new TextContent($errorMessage)], true);\n } catch (Throwable $toolError) {\n $this->logger->error('Tool execution failed.', ['tool' => $toolName, 'exception' => $toolError]);\n $errorMessage = \"Tool execution failed: {$toolError->getMessage()}\";\n\n return new CallToolResult([new TextContent($errorMessage)], true);\n }\n }\n\n public function handleResourcesList(ListResourcesRequest $request): ListResourcesResult\n {\n $limit = $this->configuration->paginationLimit;\n $offset = $this->decodeCursor($request->cursor);\n $allItems = $this->registry->getResources();\n $pagedItems = array_slice($allItems, $offset, $limit);\n $nextCursor = $this->encodeNextCursor($offset, count($pagedItems), count($allItems), $limit);\n\n return new ListResourcesResult(array_values($pagedItems), $nextCursor);\n }\n\n public function handleResourceTemplateList(ListResourceTemplatesRequest $request): ListResourceTemplatesResult\n {\n $limit = $this->configuration->paginationLimit;\n $offset = $this->decodeCursor($request->cursor);\n $allItems = $this->registry->getResourceTemplates();\n $pagedItems = array_slice($allItems, $offset, $limit);\n $nextCursor = $this->encodeNextCursor($offset, count($pagedItems), count($allItems), $limit);\n\n return new ListResourceTemplatesResult(array_values($pagedItems), $nextCursor);\n }\n\n public function handleResourceRead(ReadResourceRequest $request, Context $context): ReadResourceResult\n {\n $uri = $request->uri;\n\n $registeredResource = $this->registry->getResource($uri);\n\n if (! $registeredResource) {\n throw McpServerException::invalidParams(\"Resource URI '{$uri}' not found.\");\n }\n\n try {\n $result = $registeredResource->read($this->container, $uri, $context);\n\n return new ReadResourceResult($result);\n } catch (JsonException $e) {\n $this->logger->warning('Failed to JSON encode resource content.', ['exception' => $e, 'uri' => $uri]);\n throw McpServerException::internalError(\"Failed to serialize resource content for '{$uri}'.\", $e);\n } catch (McpServerException $e) {\n throw $e;\n } catch (Throwable $e) {\n $this->logger->error('Resource read failed.', ['uri' => $uri, 'exception' => $e]);\n throw McpServerException::resourceReadFailed($uri, $e);\n }\n }\n\n public function handleResourceSubscribe(ResourceSubscribeRequest $request, SessionInterface $session): EmptyResult\n {\n $this->subscriptionManager->subscribe($session->getId(), $request->uri);\n return new EmptyResult();\n }\n\n public function handleResourceUnsubscribe(ResourceUnsubscribeRequest $request, SessionInterface $session): EmptyResult\n {\n $this->subscriptionManager->unsubscribe($session->getId(), $request->uri);\n return new EmptyResult();\n }\n\n public function handlePromptsList(ListPromptsRequest $request): ListPromptsResult\n {\n $limit = $this->configuration->paginationLimit;\n $offset = $this->decodeCursor($request->cursor);\n $allItems = $this->registry->getPrompts();\n $pagedItems = array_slice($allItems, $offset, $limit);\n $nextCursor = $this->encodeNextCursor($offset, count($pagedItems), count($allItems), $limit);\n\n return new ListPromptsResult(array_values($pagedItems), $nextCursor);\n }\n\n public function handlePromptGet(GetPromptRequest $request, Context $context): GetPromptResult\n {\n $promptName = $request->name;\n $arguments = $request->arguments;\n\n $registeredPrompt = $this->registry->getPrompt($promptName);\n if (! $registeredPrompt) {\n throw McpServerException::invalidParams(\"Prompt '{$promptName}' not found.\");\n }\n\n $arguments = (array) $arguments;\n\n foreach ($registeredPrompt->schema->arguments as $argDef) {\n if ($argDef->required && ! array_key_exists($argDef->name, $arguments)) {\n throw McpServerException::invalidParams(\"Missing required argument '{$argDef->name}' for prompt '{$promptName}'.\");\n }\n }\n\n try {\n $result = $registeredPrompt->get($this->container, $arguments, $context);\n\n return new GetPromptResult($result, $registeredPrompt->schema->description);\n } catch (JsonException $e) {\n $this->logger->warning('Failed to JSON encode prompt messages.', ['exception' => $e, 'promptName' => $promptName]);\n throw McpServerException::internalError(\"Failed to serialize prompt messages for '{$promptName}'.\", $e);\n } catch (McpServerException $e) {\n throw $e;\n } catch (Throwable $e) {\n $this->logger->error('Prompt generation failed.', ['promptName' => $promptName, 'exception' => $e]);\n throw McpServerException::promptGenerationFailed($promptName, $e);\n }\n }\n\n public function handleLoggingSetLevel(SetLogLevelRequest $request, SessionInterface $session): EmptyResult\n {\n $level = $request->level;\n\n $session->set('log_level', $level->value);\n\n $this->logger->info(\"Log level set to '{$level->value}'.\", ['sessionId' => $session->getId()]);\n\n return new EmptyResult();\n }\n\n public function handleCompletionComplete(CompletionCompleteRequest $request, SessionInterface $session): CompletionCompleteResult\n {\n $ref = $request->ref;\n $argumentName = $request->argument['name'];\n $currentValue = $request->argument['value'];\n\n $identifier = null;\n\n if ($ref->type === 'ref/prompt') {\n $identifier = $ref->name;\n $registeredPrompt = $this->registry->getPrompt($identifier);\n if (! $registeredPrompt) {\n throw McpServerException::invalidParams(\"Prompt '{$identifier}' not found.\");\n }\n\n $foundArg = false;\n foreach ($registeredPrompt->schema->arguments as $arg) {\n if ($arg->name === $argumentName) {\n $foundArg = true;\n break;\n }\n }\n if (! $foundArg) {\n throw McpServerException::invalidParams(\"Argument '{$argumentName}' not found in prompt '{$identifier}'.\");\n }\n\n return $registeredPrompt->complete($this->container, $argumentName, $currentValue, $session);\n } elseif ($ref->type === 'ref/resource') {\n $identifier = $ref->uri;\n $registeredResourceTemplate = $this->registry->getResourceTemplate($identifier);\n if (! $registeredResourceTemplate) {\n throw McpServerException::invalidParams(\"Resource template '{$identifier}' not found.\");\n }\n\n $foundArg = false;\n foreach ($registeredResourceTemplate->getVariableNames() as $uriVariableName) {\n if ($uriVariableName === $argumentName) {\n $foundArg = true;\n break;\n }\n }\n\n if (! $foundArg) {\n throw McpServerException::invalidParams(\"URI variable '{$argumentName}' not found in resource template '{$identifier}'.\");\n }\n\n return $registeredResourceTemplate->complete($this->container, $argumentName, $currentValue, $session);\n } else {\n throw McpServerException::invalidParams(\"Invalid ref type '{$ref->type}' for completion complete request.\");\n }\n }\n\n public function handleNotificationInitialized(InitializedNotification $notification, SessionInterface $session): EmptyResult\n {\n $session->set('initialized', true);\n\n return new EmptyResult();\n }\n\n private function decodeCursor(?string $cursor): int\n {\n if ($cursor === null) {\n return 0;\n }\n\n $decoded = base64_decode($cursor, true);\n if ($decoded === false) {\n $this->logger->warning('Received invalid pagination cursor (not base64)', ['cursor' => $cursor]);\n\n return 0;\n }\n\n if (preg_match('/^offset=(\\d+)$/', $decoded, $matches)) {\n return (int) $matches[1];\n }\n\n $this->logger->warning('Received invalid pagination cursor format', ['cursor' => $decoded]);\n\n return 0;\n }\n\n private function encodeNextCursor(int $currentOffset, int $returnedCount, int $totalCount, int $limit): ?string\n {\n $nextOffset = $currentOffset + $returnedCount;\n if ($returnedCount > 0 && $nextOffset < $totalCount) {\n return base64_encode(\"offset={$nextOffset}\");\n }\n\n return null;\n }\n}\n"], ["/server/src/ServerBuilder.php", " */\n private array $manualTools = [];\n\n /** @var array<\n * array{handler: array|string|Closure,\n * uri: string,\n * name: string|null,\n * description: string|null,\n * mimeType: string|null,\n * size: int|null,\n * annotations: Annotations|null}\n * > */\n private array $manualResources = [];\n\n /** @var array<\n * array{handler: array|string|Closure,\n * uriTemplate: string,\n * name: string|null,\n * description: string|null,\n * mimeType: string|null,\n * annotations: Annotations|null}\n * > */\n private array $manualResourceTemplates = [];\n\n /** @var array<\n * array{handler: array|string|Closure,\n * name: string|null,\n * description: string|null}\n * > */\n private array $manualPrompts = [];\n\n public function __construct() {}\n\n /**\n * Sets the server's identity. Required.\n */\n public function withServerInfo(string $name, string $version): self\n {\n $this->serverInfo = Implementation::make(name: trim($name), version: trim($version));\n\n return $this;\n }\n\n /**\n * Configures the server's declared capabilities.\n */\n public function withCapabilities(ServerCapabilities $capabilities): self\n {\n $this->capabilities = $capabilities;\n\n return $this;\n }\n\n /**\n * Configures the server's pagination limit.\n */\n public function withPaginationLimit(int $paginationLimit): self\n {\n $this->paginationLimit = $paginationLimit;\n\n return $this;\n }\n\n /**\n * Configures the instructions describing how to use the server and its features. \n * \n * This can be used by clients to improve the LLM's understanding of available tools, resources,\n * etc. It can be thought of like a \"hint\" to the model. For example, this information MAY \n * be added to the system prompt.\n */\n public function withInstructions(?string $instructions): self\n {\n $this->instructions = $instructions;\n\n return $this;\n }\n\n /**\n * Provides a PSR-3 logger instance. Defaults to NullLogger.\n */\n public function withLogger(LoggerInterface $logger): self\n {\n $this->logger = $logger;\n\n return $this;\n }\n\n /**\n * Provides a PSR-16 cache instance used for all internal caching.\n */\n public function withCache(CacheInterface $cache): self\n {\n $this->cache = $cache;\n\n return $this;\n }\n\n /**\n * Configures session handling with a specific driver.\n * \n * @param 'array' | 'cache' $driver The session driver: 'array' for in-memory sessions, 'cache' for cache-backed sessions\n * @param int $ttl Session time-to-live in seconds. Defaults to 3600.\n */\n public function withSession(string $driver, int $ttl = 3600): self\n {\n if (!in_array($driver, ['array', 'cache'], true)) {\n throw new \\InvalidArgumentException(\n \"Unsupported session driver '{$driver}'. Only 'array' and 'cache' drivers are supported. \" .\n \"For custom session handling, use withSessionHandler() instead.\"\n );\n }\n\n $this->sessionDriver = $driver;\n $this->sessionTtl = $ttl;\n\n return $this;\n }\n\n /**\n * Provides a custom session handler.\n */\n public function withSessionHandler(SessionHandlerInterface $sessionHandler, int $sessionTtl = 3600): self\n {\n $this->sessionHandler = $sessionHandler;\n $this->sessionTtl = $sessionTtl;\n\n return $this;\n }\n\n /**\n * Provides a PSR-11 DI container, primarily for resolving user-defined handler classes.\n * Defaults to a basic internal container.\n */\n public function withContainer(ContainerInterface $container): self\n {\n $this->container = $container;\n\n return $this;\n }\n\n /**\n * Provides a ReactPHP Event Loop instance. Defaults to Loop::get().\n */\n public function withLoop(LoopInterface $loop): self\n {\n $this->loop = $loop;\n\n return $this;\n }\n\n /**\n * Manually registers a tool handler.\n */\n public function withTool(callable|array|string $handler, ?string $name = null, ?string $description = null, ?ToolAnnotations $annotations = null, ?array $inputSchema = null): self\n {\n $this->manualTools[] = compact('handler', 'name', 'description', 'annotations', 'inputSchema');\n\n return $this;\n }\n\n /**\n * Manually registers a resource handler.\n */\n public function withResource(callable|array|string $handler, string $uri, ?string $name = null, ?string $description = null, ?string $mimeType = null, ?int $size = null, ?Annotations $annotations = null): self\n {\n $this->manualResources[] = compact('handler', 'uri', 'name', 'description', 'mimeType', 'size', 'annotations');\n\n return $this;\n }\n\n /**\n * Manually registers a resource template handler.\n */\n public function withResourceTemplate(callable|array|string $handler, string $uriTemplate, ?string $name = null, ?string $description = null, ?string $mimeType = null, ?Annotations $annotations = null): self\n {\n $this->manualResourceTemplates[] = compact('handler', 'uriTemplate', 'name', 'description', 'mimeType', 'annotations');\n\n return $this;\n }\n\n /**\n * Manually registers a prompt handler.\n */\n public function withPrompt(callable|array|string $handler, ?string $name = null, ?string $description = null): self\n {\n $this->manualPrompts[] = compact('handler', 'name', 'description');\n\n return $this;\n }\n\n /**\n * Builds the fully configured Server instance.\n *\n * @throws ConfigurationException If required configuration is missing.\n */\n public function build(): Server\n {\n if ($this->serverInfo === null) {\n throw new ConfigurationException('Server name and version must be provided using withServerInfo().');\n }\n\n $loop = $this->loop ?? Loop::get();\n $cache = $this->cache;\n $logger = $this->logger ?? new NullLogger();\n $container = $this->container ?? new BasicContainer();\n $capabilities = $this->capabilities ?? ServerCapabilities::make();\n\n $configuration = new Configuration(\n serverInfo: $this->serverInfo,\n capabilities: $capabilities,\n logger: $logger,\n loop: $loop,\n cache: $cache,\n container: $container,\n paginationLimit: $this->paginationLimit ?? 50,\n instructions: $this->instructions,\n );\n\n $sessionHandler = $this->createSessionHandler();\n $sessionManager = new SessionManager($sessionHandler, $logger, $loop, $this->sessionTtl);\n $registry = new Registry($logger, $cache, $sessionManager);\n $protocol = new Protocol($configuration, $registry, $sessionManager);\n\n $registry->disableNotifications();\n\n $this->registerManualElements($registry, $logger);\n\n $registry->enableNotifications();\n\n $server = new Server($configuration, $registry, $protocol, $sessionManager);\n\n return $server;\n }\n\n /**\n * Helper to perform the actual registration based on stored data.\n * Moved into the builder.\n */\n private function registerManualElements(Registry $registry, LoggerInterface $logger): void\n {\n if (empty($this->manualTools) && empty($this->manualResources) && empty($this->manualResourceTemplates) && empty($this->manualPrompts)) {\n return;\n }\n\n $docBlockParser = new Utils\\DocBlockParser($logger);\n $schemaGenerator = new Utils\\SchemaGenerator($docBlockParser);\n\n // Register Tools\n foreach ($this->manualTools as $data) {\n try {\n $reflection = HandlerResolver::resolve($data['handler']);\n\n if ($reflection instanceof \\ReflectionFunction) {\n $name = $data['name'] ?? 'closure_tool_' . spl_object_id($data['handler']);\n $description = $data['description'] ?? null;\n } else {\n $classShortName = $reflection->getDeclaringClass()->getShortName();\n $methodName = $reflection->getName();\n $docBlock = $docBlockParser->parseDocBlock($reflection->getDocComment() ?? null);\n\n $name = $data['name'] ?? ($methodName === '__invoke' ? $classShortName : $methodName);\n $description = $data['description'] ?? $docBlockParser->getSummary($docBlock) ?? null;\n }\n\n $inputSchema = $data['inputSchema'] ?? $schemaGenerator->generate($reflection);\n\n $tool = Tool::make($name, $inputSchema, $description, $data['annotations']);\n $registry->registerTool($tool, $data['handler'], true);\n\n $handlerDesc = $data['handler'] instanceof \\Closure ? 'Closure' : (is_array($data['handler']) ? implode('::', $data['handler']) : $data['handler']);\n $logger->debug(\"Registered manual tool {$name} from handler {$handlerDesc}\");\n } catch (Throwable $e) {\n $logger->error('Failed to register manual tool', ['handler' => $data['handler'], 'name' => $data['name'], 'exception' => $e]);\n throw new ConfigurationException(\"Error registering manual tool '{$data['name']}': {$e->getMessage()}\", 0, $e);\n }\n }\n\n // Register Resources\n foreach ($this->manualResources as $data) {\n try {\n $reflection = HandlerResolver::resolve($data['handler']);\n\n if ($reflection instanceof \\ReflectionFunction) {\n $name = $data['name'] ?? 'closure_resource_' . spl_object_id($data['handler']);\n $description = $data['description'] ?? null;\n } else {\n $classShortName = $reflection->getDeclaringClass()->getShortName();\n $methodName = $reflection->getName();\n $docBlock = $docBlockParser->parseDocBlock($reflection->getDocComment() ?? null);\n\n $name = $data['name'] ?? ($methodName === '__invoke' ? $classShortName : $methodName);\n $description = $data['description'] ?? $docBlockParser->getSummary($docBlock) ?? null;\n }\n\n $uri = $data['uri'];\n $mimeType = $data['mimeType'];\n $size = $data['size'];\n $annotations = $data['annotations'];\n\n $resource = Resource::make($uri, $name, $description, $mimeType, $annotations, $size);\n $registry->registerResource($resource, $data['handler'], true);\n\n $handlerDesc = $data['handler'] instanceof \\Closure ? 'Closure' : (is_array($data['handler']) ? implode('::', $data['handler']) : $data['handler']);\n $logger->debug(\"Registered manual resource {$name} from handler {$handlerDesc}\");\n } catch (Throwable $e) {\n $logger->error('Failed to register manual resource', ['handler' => $data['handler'], 'uri' => $data['uri'], 'exception' => $e]);\n throw new ConfigurationException(\"Error registering manual resource '{$data['uri']}': {$e->getMessage()}\", 0, $e);\n }\n }\n\n // Register Templates\n foreach ($this->manualResourceTemplates as $data) {\n try {\n $reflection = HandlerResolver::resolve($data['handler']);\n\n if ($reflection instanceof \\ReflectionFunction) {\n $name = $data['name'] ?? 'closure_template_' . spl_object_id($data['handler']);\n $description = $data['description'] ?? null;\n } else {\n $classShortName = $reflection->getDeclaringClass()->getShortName();\n $methodName = $reflection->getName();\n $docBlock = $docBlockParser->parseDocBlock($reflection->getDocComment() ?? null);\n\n $name = $data['name'] ?? ($methodName === '__invoke' ? $classShortName : $methodName);\n $description = $data['description'] ?? $docBlockParser->getSummary($docBlock) ?? null;\n }\n\n $uriTemplate = $data['uriTemplate'];\n $mimeType = $data['mimeType'];\n $annotations = $data['annotations'];\n\n $template = ResourceTemplate::make($uriTemplate, $name, $description, $mimeType, $annotations);\n $completionProviders = $this->getCompletionProviders($reflection);\n $registry->registerResourceTemplate($template, $data['handler'], $completionProviders, true);\n\n $handlerDesc = $data['handler'] instanceof \\Closure ? 'Closure' : (is_array($data['handler']) ? implode('::', $data['handler']) : $data['handler']);\n $logger->debug(\"Registered manual template {$name} from handler {$handlerDesc}\");\n } catch (Throwable $e) {\n $logger->error('Failed to register manual template', ['handler' => $data['handler'], 'uriTemplate' => $data['uriTemplate'], 'exception' => $e]);\n throw new ConfigurationException(\"Error registering manual resource template '{$data['uriTemplate']}': {$e->getMessage()}\", 0, $e);\n }\n }\n\n // Register Prompts\n foreach ($this->manualPrompts as $data) {\n try {\n $reflection = HandlerResolver::resolve($data['handler']);\n\n if ($reflection instanceof \\ReflectionFunction) {\n $name = $data['name'] ?? 'closure_prompt_' . spl_object_id($data['handler']);\n $description = $data['description'] ?? null;\n } else {\n $classShortName = $reflection->getDeclaringClass()->getShortName();\n $methodName = $reflection->getName();\n $docBlock = $docBlockParser->parseDocBlock($reflection->getDocComment() ?? null);\n\n $name = $data['name'] ?? ($methodName === '__invoke' ? $classShortName : $methodName);\n $description = $data['description'] ?? $docBlockParser->getSummary($docBlock) ?? null;\n }\n\n $arguments = [];\n $paramTags = $reflection instanceof \\ReflectionMethod ? $docBlockParser->getParamTags($docBlockParser->parseDocBlock($reflection->getDocComment() ?? null)) : [];\n foreach ($reflection->getParameters() as $param) {\n $reflectionType = $param->getType();\n\n // Basic DI check (heuristic)\n if ($reflectionType instanceof \\ReflectionNamedType && ! $reflectionType->isBuiltin()) {\n continue;\n }\n\n $paramTag = $paramTags['$' . $param->getName()] ?? null;\n $arguments[] = PromptArgument::make(\n name: $param->getName(),\n description: $paramTag ? trim((string) $paramTag->getDescription()) : null,\n required: ! $param->isOptional() && ! $param->isDefaultValueAvailable()\n );\n }\n\n $prompt = Prompt::make($name, $description, $arguments);\n $completionProviders = $this->getCompletionProviders($reflection);\n $registry->registerPrompt($prompt, $data['handler'], $completionProviders, true);\n\n $handlerDesc = $data['handler'] instanceof \\Closure ? 'Closure' : (is_array($data['handler']) ? implode('::', $data['handler']) : $data['handler']);\n $logger->debug(\"Registered manual prompt {$name} from handler {$handlerDesc}\");\n } catch (Throwable $e) {\n $logger->error('Failed to register manual prompt', ['handler' => $data['handler'], 'name' => $data['name'], 'exception' => $e]);\n throw new ConfigurationException(\"Error registering manual prompt '{$data['name']}': {$e->getMessage()}\", 0, $e);\n }\n }\n\n $logger->debug('Manual element registration complete.');\n }\n\n /**\n * Creates the appropriate session handler based on configuration.\n * \n * @throws ConfigurationException If cache driver is selected but no cache is provided\n */\n private function createSessionHandler(): SessionHandlerInterface\n {\n // If a custom session handler was provided, use it\n if ($this->sessionHandler !== null) {\n return $this->sessionHandler;\n }\n\n // If no session driver was specified, default to array\n if ($this->sessionDriver === null) {\n return new ArraySessionHandler($this->sessionTtl ?? 3600);\n }\n\n // Create handler based on driver\n return match ($this->sessionDriver) {\n 'array' => new ArraySessionHandler($this->sessionTtl ?? 3600),\n 'cache' => $this->createCacheSessionHandler(),\n default => throw new ConfigurationException(\"Unsupported session driver: {$this->sessionDriver}\")\n };\n }\n\n /**\n * Creates a cache-based session handler.\n * \n * @throws ConfigurationException If no cache is configured\n */\n private function createCacheSessionHandler(): CacheSessionHandler\n {\n if ($this->cache === null) {\n throw new ConfigurationException(\n \"Cache session driver requires a cache instance. Please configure a cache using withCache() before using withSession('cache').\"\n );\n }\n\n return new CacheSessionHandler($this->cache, $this->sessionTtl ?? 3600);\n }\n\n private function getCompletionProviders(\\ReflectionMethod|\\ReflectionFunction $reflection): array\n {\n $completionProviders = [];\n foreach ($reflection->getParameters() as $param) {\n $reflectionType = $param->getType();\n if ($reflectionType instanceof \\ReflectionNamedType && !$reflectionType->isBuiltin()) {\n continue;\n }\n\n $completionAttributes = $param->getAttributes(CompletionProvider::class, \\ReflectionAttribute::IS_INSTANCEOF);\n if (!empty($completionAttributes)) {\n $attributeInstance = $completionAttributes[0]->newInstance();\n\n if ($attributeInstance->provider) {\n $completionProviders[$param->getName()] = $attributeInstance->provider;\n } elseif ($attributeInstance->providerClass) {\n $completionProviders[$param->getName()] = $attributeInstance->providerClass;\n } elseif ($attributeInstance->values) {\n $completionProviders[$param->getName()] = new ListCompletionProvider($attributeInstance->values);\n } elseif ($attributeInstance->enum) {\n $completionProviders[$param->getName()] = new EnumCompletionProvider($attributeInstance->enum);\n }\n }\n }\n\n return $completionProviders;\n }\n}\n"], ["/server/src/Utils/Discoverer.php", "docBlockParser = $docBlockParser ?? new DocBlockParser($this->logger);\n $this->schemaGenerator = $schemaGenerator ?? new SchemaGenerator($this->docBlockParser);\n }\n\n /**\n * Discover MCP elements in the specified directories.\n *\n * @param string $basePath The base path for resolving directories.\n * @param array $directories List of directories (relative to base path) to scan.\n * @param array $excludeDirs List of directories (relative to base path) to exclude from the scan.\n */\n public function discover(string $basePath, array $directories, array $excludeDirs = []): void\n {\n $startTime = microtime(true);\n $discoveredCount = [\n 'tools' => 0,\n 'resources' => 0,\n 'prompts' => 0,\n 'resourceTemplates' => 0,\n ];\n\n try {\n $finder = new Finder();\n $absolutePaths = [];\n foreach ($directories as $dir) {\n $path = rtrim($basePath, '/') . '/' . ltrim($dir, '/');\n if (is_dir($path)) {\n $absolutePaths[] = $path;\n }\n }\n\n if (empty($absolutePaths)) {\n $this->logger->warning('No valid discovery directories found to scan.', ['configured_paths' => $directories, 'base_path' => $basePath]);\n\n return;\n }\n\n $finder->files()\n ->in($absolutePaths)\n ->exclude($excludeDirs)\n ->name('*.php');\n\n foreach ($finder as $file) {\n $this->processFile($file, $discoveredCount);\n }\n } catch (Throwable $e) {\n $this->logger->error('Error during file finding process for MCP discovery', [\n 'exception' => $e->getMessage(),\n 'trace' => $e->getTraceAsString(),\n ]);\n }\n\n $duration = microtime(true) - $startTime;\n $this->logger->info('Attribute discovery finished.', [\n 'duration_sec' => round($duration, 3),\n 'tools' => $discoveredCount['tools'],\n 'resources' => $discoveredCount['resources'],\n 'prompts' => $discoveredCount['prompts'],\n 'resourceTemplates' => $discoveredCount['resourceTemplates'],\n ]);\n }\n\n /**\n * Process a single PHP file for MCP elements on classes or methods.\n */\n private function processFile(SplFileInfo $file, array &$discoveredCount): void\n {\n $filePath = $file->getRealPath();\n if ($filePath === false) {\n $this->logger->warning('Could not get real path for file', ['path' => $file->getPathname()]);\n\n return;\n }\n\n $className = $this->getClassFromFile($filePath);\n if (! $className) {\n $this->logger->warning('No valid class found in file', ['file' => $filePath]);\n\n return;\n }\n\n try {\n $reflectionClass = new ReflectionClass($className);\n\n if ($reflectionClass->isAbstract() || $reflectionClass->isInterface() || $reflectionClass->isTrait() || $reflectionClass->isEnum()) {\n return;\n }\n\n $processedViaClassAttribute = false;\n if ($reflectionClass->hasMethod('__invoke')) {\n $invokeMethod = $reflectionClass->getMethod('__invoke');\n if ($invokeMethod->isPublic() && ! $invokeMethod->isStatic()) {\n $attributeTypes = [McpTool::class, McpResource::class, McpPrompt::class, McpResourceTemplate::class];\n foreach ($attributeTypes as $attributeType) {\n $classAttribute = $reflectionClass->getAttributes($attributeType, ReflectionAttribute::IS_INSTANCEOF)[0] ?? null;\n if ($classAttribute) {\n $this->processMethod($invokeMethod, $discoveredCount, $classAttribute);\n $processedViaClassAttribute = true;\n break;\n }\n }\n }\n }\n\n if (! $processedViaClassAttribute) {\n foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {\n if (\n $method->getDeclaringClass()->getName() !== $reflectionClass->getName() ||\n $method->isStatic() || $method->isAbstract() || $method->isConstructor() || $method->isDestructor() || $method->getName() === '__invoke'\n ) {\n continue;\n }\n $attributeTypes = [McpTool::class, McpResource::class, McpPrompt::class, McpResourceTemplate::class];\n foreach ($attributeTypes as $attributeType) {\n $methodAttribute = $method->getAttributes($attributeType, ReflectionAttribute::IS_INSTANCEOF)[0] ?? null;\n if ($methodAttribute) {\n $this->processMethod($method, $discoveredCount, $methodAttribute);\n break;\n }\n }\n }\n }\n } catch (ReflectionException $e) {\n $this->logger->error('Reflection error processing file for MCP discovery', ['file' => $filePath, 'class' => $className, 'exception' => $e->getMessage()]);\n } catch (Throwable $e) {\n $this->logger->error('Unexpected error processing file for MCP discovery', [\n 'file' => $filePath,\n 'class' => $className,\n 'exception' => $e->getMessage(),\n 'trace' => $e->getTraceAsString(),\n ]);\n }\n }\n\n /**\n * Process a method with a given MCP attribute instance.\n * Can be called for regular methods or the __invoke method of an invokable class.\n *\n * @param ReflectionMethod $method The target method (e.g., regular method or __invoke).\n * @param array $discoveredCount Pass by reference to update counts.\n * @param ReflectionAttribute $attribute The ReflectionAttribute instance found (on method or class).\n */\n private function processMethod(ReflectionMethod $method, array &$discoveredCount, ReflectionAttribute $attribute): void\n {\n $className = $method->getDeclaringClass()->getName();\n $classShortName = $method->getDeclaringClass()->getShortName();\n $methodName = $method->getName();\n $attributeClassName = $attribute->getName();\n\n try {\n $instance = $attribute->newInstance();\n\n switch ($attributeClassName) {\n case McpTool::class:\n $docBlock = $this->docBlockParser->parseDocBlock($method->getDocComment() ?? null);\n $name = $instance->name ?? ($methodName === '__invoke' ? $classShortName : $methodName);\n $description = $instance->description ?? $this->docBlockParser->getSummary($docBlock) ?? null;\n $inputSchema = $this->schemaGenerator->generate($method);\n $tool = Tool::make($name, $inputSchema, $description, $instance->annotations);\n $this->registry->registerTool($tool, [$className, $methodName]);\n $discoveredCount['tools']++;\n break;\n\n case McpResource::class:\n $docBlock = $this->docBlockParser->parseDocBlock($method->getDocComment() ?? null);\n $name = $instance->name ?? ($methodName === '__invoke' ? $classShortName : $methodName);\n $description = $instance->description ?? $this->docBlockParser->getSummary($docBlock) ?? null;\n $mimeType = $instance->mimeType;\n $size = $instance->size;\n $annotations = $instance->annotations;\n $resource = Resource::make($instance->uri, $name, $description, $mimeType, $annotations, $size);\n $this->registry->registerResource($resource, [$className, $methodName]);\n $discoveredCount['resources']++;\n break;\n\n case McpPrompt::class:\n $docBlock = $this->docBlockParser->parseDocBlock($method->getDocComment() ?? null);\n $name = $instance->name ?? ($methodName === '__invoke' ? $classShortName : $methodName);\n $description = $instance->description ?? $this->docBlockParser->getSummary($docBlock) ?? null;\n $arguments = [];\n $paramTags = $this->docBlockParser->getParamTags($docBlock);\n foreach ($method->getParameters() as $param) {\n $reflectionType = $param->getType();\n if ($reflectionType instanceof \\ReflectionNamedType && ! $reflectionType->isBuiltin()) {\n continue;\n }\n $paramTag = $paramTags['$' . $param->getName()] ?? null;\n $arguments[] = PromptArgument::make($param->getName(), $paramTag ? trim((string) $paramTag->getDescription()) : null, ! $param->isOptional() && ! $param->isDefaultValueAvailable());\n }\n $prompt = Prompt::make($name, $description, $arguments);\n $completionProviders = $this->getCompletionProviders($method);\n $this->registry->registerPrompt($prompt, [$className, $methodName], $completionProviders);\n $discoveredCount['prompts']++;\n break;\n\n case McpResourceTemplate::class:\n $docBlock = $this->docBlockParser->parseDocBlock($method->getDocComment() ?? null);\n $name = $instance->name ?? ($methodName === '__invoke' ? $classShortName : $methodName);\n $description = $instance->description ?? $this->docBlockParser->getSummary($docBlock) ?? null;\n $mimeType = $instance->mimeType;\n $annotations = $instance->annotations;\n $resourceTemplate = ResourceTemplate::make($instance->uriTemplate, $name, $description, $mimeType, $annotations);\n $completionProviders = $this->getCompletionProviders($method);\n $this->registry->registerResourceTemplate($resourceTemplate, [$className, $methodName], $completionProviders);\n $discoveredCount['resourceTemplates']++;\n break;\n }\n } catch (McpServerException $e) {\n $this->logger->error(\"Failed to process MCP attribute on {$className}::{$methodName}\", ['attribute' => $attributeClassName, 'exception' => $e->getMessage(), 'trace' => $e->getPrevious() ? $e->getPrevious()->getTraceAsString() : $e->getTraceAsString()]);\n } catch (Throwable $e) {\n $this->logger->error(\"Unexpected error processing attribute on {$className}::{$methodName}\", ['attribute' => $attributeClassName, 'exception' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);\n }\n }\n\n private function getCompletionProviders(\\ReflectionMethod $reflectionMethod): array\n {\n $completionProviders = [];\n foreach ($reflectionMethod->getParameters() as $param) {\n $reflectionType = $param->getType();\n if ($reflectionType instanceof \\ReflectionNamedType && ! $reflectionType->isBuiltin()) {\n continue;\n }\n\n $completionAttributes = $param->getAttributes(CompletionProvider::class, \\ReflectionAttribute::IS_INSTANCEOF);\n if (!empty($completionAttributes)) {\n $attributeInstance = $completionAttributes[0]->newInstance();\n\n if ($attributeInstance->provider) {\n $completionProviders[$param->getName()] = $attributeInstance->provider;\n } elseif ($attributeInstance->providerClass) {\n $completionProviders[$param->getName()] = $attributeInstance->provider;\n } elseif ($attributeInstance->values) {\n $completionProviders[$param->getName()] = new ListCompletionProvider($attributeInstance->values);\n } elseif ($attributeInstance->enum) {\n $completionProviders[$param->getName()] = new EnumCompletionProvider($attributeInstance->enum);\n }\n }\n }\n\n return $completionProviders;\n }\n\n /**\n * Attempt to determine the FQCN from a PHP file path.\n * Uses tokenization to extract namespace and class name.\n *\n * @param string $filePath Absolute path to the PHP file.\n * @return class-string|null The FQCN or null if not found/determinable.\n */\n private function getClassFromFile(string $filePath): ?string\n {\n if (! file_exists($filePath) || ! is_readable($filePath)) {\n $this->logger->warning('File does not exist or is not readable.', ['file' => $filePath]);\n\n return null;\n }\n\n try {\n $content = file_get_contents($filePath);\n if ($content === false) {\n $this->logger->warning('Failed to read file content.', ['file' => $filePath]);\n\n return null;\n }\n if (strlen($content) > 500 * 1024) {\n $this->logger->debug('Skipping large file during class discovery.', ['file' => $filePath]);\n\n return null;\n }\n\n $tokens = token_get_all($content);\n } catch (Throwable $e) {\n $this->logger->warning(\"Failed to read or tokenize file during class discovery: {$filePath}\", ['exception' => $e->getMessage()]);\n\n return null;\n }\n\n $namespace = '';\n $namespaceFound = false;\n $level = 0;\n $potentialClasses = [];\n\n $tokenCount = count($tokens);\n for ($i = 0; $i < $tokenCount; $i++) {\n if (is_array($tokens[$i]) && $tokens[$i][0] === T_NAMESPACE) {\n $namespace = '';\n for ($j = $i + 1; $j < $tokenCount; $j++) {\n if ($tokens[$j] === ';' || $tokens[$j] === '{') {\n $namespaceFound = true;\n $i = $j;\n break;\n }\n if (is_array($tokens[$j]) && in_array($tokens[$j][0], [T_STRING, T_NAME_QUALIFIED])) {\n $namespace .= $tokens[$j][1];\n } elseif ($tokens[$j][0] === T_NS_SEPARATOR) {\n $namespace .= '\\\\';\n }\n }\n if ($namespaceFound) {\n break;\n }\n }\n }\n $namespace = trim($namespace, '\\\\');\n\n for ($i = 0; $i < $tokenCount; $i++) {\n $token = $tokens[$i];\n if ($token === '{') {\n $level++;\n\n continue;\n }\n if ($token === '}') {\n $level--;\n\n continue;\n }\n\n if ($level === ($namespaceFound && str_contains($content, \"namespace {$namespace} {\") ? 1 : 0)) {\n if (is_array($token) && in_array($token[0], [T_CLASS, T_INTERFACE, T_TRAIT, defined('T_ENUM') ? T_ENUM : -1])) {\n for ($j = $i + 1; $j < $tokenCount; $j++) {\n if (is_array($tokens[$j]) && $tokens[$j][0] === T_STRING) {\n $className = $tokens[$j][1];\n $potentialClasses[] = $namespace ? $namespace . '\\\\' . $className : $className;\n $i = $j;\n break;\n }\n if ($tokens[$j] === ';' || $tokens[$j] === '{' || $tokens[$j] === ')') {\n break;\n }\n }\n }\n }\n }\n\n foreach ($potentialClasses as $potentialClass) {\n if (class_exists($potentialClass, true)) {\n return $potentialClass;\n }\n }\n\n if (! empty($potentialClasses)) {\n if (! class_exists($potentialClasses[0], false)) {\n $this->logger->debug('getClassFromFile returning potential non-class type. Are you sure this class has been autoloaded?', ['file' => $filePath, 'type' => $potentialClasses[0]]);\n }\n\n return $potentialClasses[0];\n }\n\n return null;\n }\n}\n"], ["/server/src/Registry.php", " */\n private array $tools = [];\n\n /** @var array */\n private array $resources = [];\n\n /** @var array */\n private array $prompts = [];\n\n /** @var array */\n private array $resourceTemplates = [];\n\n private array $listHashes = [\n 'tools' => '',\n 'resources' => '',\n 'resource_templates' => '',\n 'prompts' => '',\n ];\n\n private bool $notificationsEnabled = true;\n\n public function __construct(\n protected LoggerInterface $logger,\n protected ?CacheInterface $cache = null,\n ) {\n $this->load();\n $this->computeAllHashes();\n }\n\n /**\n * Compute hashes for all lists for change detection\n */\n private function computeAllHashes(): void\n {\n $this->listHashes['tools'] = $this->computeHash($this->tools);\n $this->listHashes['resources'] = $this->computeHash($this->resources);\n $this->listHashes['resource_templates'] = $this->computeHash($this->resourceTemplates);\n $this->listHashes['prompts'] = $this->computeHash($this->prompts);\n }\n\n /**\n * Compute a stable hash for a collection\n */\n private function computeHash(array $collection): string\n {\n if (empty($collection)) {\n return '';\n }\n\n ksort($collection);\n return md5(json_encode($collection));\n }\n\n public function load(): void\n {\n if ($this->cache === null) {\n return;\n }\n\n $this->clear(false);\n\n try {\n $cached = $this->cache->get(self::DISCOVERED_ELEMENTS_CACHE_KEY);\n\n if (!is_array($cached)) {\n $this->logger->warning('Invalid or missing data found in registry cache, ignoring.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY, 'type' => gettype($cached)]);\n return;\n }\n\n $loadCount = 0;\n\n foreach ($cached['tools'] ?? [] as $toolData) {\n $cachedTool = RegisteredTool::fromArray(json_decode($toolData, true));\n if ($cachedTool === false) {\n $this->logger->warning('Invalid or missing data found in registry cache, ignoring.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY, 'type' => gettype($cached)]);\n continue;\n }\n\n $toolName = $cachedTool->schema->name;\n $existingTool = $this->tools[$toolName] ?? null;\n\n if ($existingTool && $existingTool->isManual) {\n $this->logger->debug(\"Skipping cached tool '{$toolName}' as manual version exists.\");\n continue;\n }\n\n $this->tools[$toolName] = $cachedTool;\n $loadCount++;\n }\n\n foreach ($cached['resources'] ?? [] as $resourceData) {\n $cachedResource = RegisteredResource::fromArray(json_decode($resourceData, true));\n if ($cachedResource === false) {\n $this->logger->warning('Invalid or missing data found in registry cache, ignoring.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY, 'type' => gettype($cached)]);\n continue;\n }\n\n $uri = $cachedResource->schema->uri;\n $existingResource = $this->resources[$uri] ?? null;\n\n if ($existingResource && $existingResource->isManual) {\n $this->logger->debug(\"Skipping cached resource '{$uri}' as manual version exists.\");\n continue;\n }\n\n $this->resources[$uri] = $cachedResource;\n $loadCount++;\n }\n\n foreach ($cached['prompts'] ?? [] as $promptData) {\n $cachedPrompt = RegisteredPrompt::fromArray(json_decode($promptData, true));\n if ($cachedPrompt === false) {\n $this->logger->warning('Invalid or missing data found in registry cache, ignoring.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY, 'type' => gettype($cached)]);\n continue;\n }\n\n $promptName = $cachedPrompt->schema->name;\n $existingPrompt = $this->prompts[$promptName] ?? null;\n\n if ($existingPrompt && $existingPrompt->isManual) {\n $this->logger->debug(\"Skipping cached prompt '{$promptName}' as manual version exists.\");\n continue;\n }\n\n $this->prompts[$promptName] = $cachedPrompt;\n $loadCount++;\n }\n\n foreach ($cached['resourceTemplates'] ?? [] as $templateData) {\n $cachedTemplate = RegisteredResourceTemplate::fromArray(json_decode($templateData, true));\n if ($cachedTemplate === false) {\n $this->logger->warning('Invalid or missing data found in registry cache, ignoring.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY, 'type' => gettype($cached)]);\n continue;\n }\n\n $uriTemplate = $cachedTemplate->schema->uriTemplate;\n $existingTemplate = $this->resourceTemplates[$uriTemplate] ?? null;\n\n if ($existingTemplate && $existingTemplate->isManual) {\n $this->logger->debug(\"Skipping cached template '{$uriTemplate}' as manual version exists.\");\n continue;\n }\n\n $this->resourceTemplates[$uriTemplate] = $cachedTemplate;\n $loadCount++;\n }\n\n $this->logger->debug(\"Loaded {$loadCount} elements from cache.\");\n } catch (CacheInvalidArgumentException $e) {\n $this->logger->error('Invalid registry cache key used.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY, 'exception' => $e]);\n } catch (Throwable $e) {\n $this->logger->error('Unexpected error loading from cache.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY, 'exception' => $e]);\n }\n }\n\n public function registerTool(Tool $tool, callable|array|string $handler, bool $isManual = false): void\n {\n $toolName = $tool->name;\n $existing = $this->tools[$toolName] ?? null;\n\n if ($existing && ! $isManual && $existing->isManual) {\n $this->logger->debug(\"Ignoring discovered tool '{$toolName}' as it conflicts with a manually registered one.\");\n\n return;\n }\n\n $this->tools[$toolName] = RegisteredTool::make($tool, $handler, $isManual);\n\n $this->checkAndEmitChange('tools', $this->tools);\n }\n\n public function registerResource(Resource $resource, callable|array|string $handler, bool $isManual = false): void\n {\n $uri = $resource->uri;\n $existing = $this->resources[$uri] ?? null;\n\n if ($existing && ! $isManual && $existing->isManual) {\n $this->logger->debug(\"Ignoring discovered resource '{$uri}' as it conflicts with a manually registered one.\");\n\n return;\n }\n\n $this->resources[$uri] = RegisteredResource::make($resource, $handler, $isManual);\n\n $this->checkAndEmitChange('resources', $this->resources);\n }\n\n public function registerResourceTemplate(\n ResourceTemplate $template,\n callable|array|string $handler,\n array $completionProviders = [],\n bool $isManual = false,\n ): void {\n $uriTemplate = $template->uriTemplate;\n $existing = $this->resourceTemplates[$uriTemplate] ?? null;\n\n if ($existing && ! $isManual && $existing->isManual) {\n $this->logger->debug(\"Ignoring discovered template '{$uriTemplate}' as it conflicts with a manually registered one.\");\n\n return;\n }\n\n $this->resourceTemplates[$uriTemplate] = RegisteredResourceTemplate::make($template, $handler, $isManual, $completionProviders);\n\n $this->checkAndEmitChange('resource_templates', $this->resourceTemplates);\n }\n\n public function registerPrompt(\n Prompt $prompt,\n callable|array|string $handler,\n array $completionProviders = [],\n bool $isManual = false,\n ): void {\n $promptName = $prompt->name;\n $existing = $this->prompts[$promptName] ?? null;\n\n if ($existing && ! $isManual && $existing->isManual) {\n $this->logger->debug(\"Ignoring discovered prompt '{$promptName}' as it conflicts with a manually registered one.\");\n\n return;\n }\n\n $this->prompts[$promptName] = RegisteredPrompt::make($prompt, $handler, $isManual, $completionProviders);\n\n $this->checkAndEmitChange('prompts', $this->prompts);\n }\n\n public function enableNotifications(): void\n {\n $this->notificationsEnabled = true;\n }\n\n public function disableNotifications(): void\n {\n $this->notificationsEnabled = false;\n }\n\n /**\n * Check if a list has changed and emit event if needed\n */\n private function checkAndEmitChange(string $listType, array $collection): void\n {\n if (! $this->notificationsEnabled) {\n return;\n }\n\n $newHash = $this->computeHash($collection);\n\n if ($newHash !== $this->listHashes[$listType]) {\n $this->listHashes[$listType] = $newHash;\n $this->emit('list_changed', [$listType]);\n }\n }\n\n public function save(): bool\n {\n if ($this->cache === null) {\n return false;\n }\n\n $discoveredData = [\n 'tools' => [],\n 'resources' => [],\n 'prompts' => [],\n 'resourceTemplates' => [],\n ];\n\n foreach ($this->tools as $name => $tool) {\n if (! $tool->isManual) {\n if ($tool->handler instanceof \\Closure) {\n $this->logger->warning(\"Skipping closure tool from cache: {$name}\");\n continue;\n }\n $discoveredData['tools'][$name] = json_encode($tool);\n }\n }\n\n foreach ($this->resources as $uri => $resource) {\n if (! $resource->isManual) {\n if ($resource->handler instanceof \\Closure) {\n $this->logger->warning(\"Skipping closure resource from cache: {$uri}\");\n continue;\n }\n $discoveredData['resources'][$uri] = json_encode($resource);\n }\n }\n\n foreach ($this->prompts as $name => $prompt) {\n if (! $prompt->isManual) {\n if ($prompt->handler instanceof \\Closure) {\n $this->logger->warning(\"Skipping closure prompt from cache: {$name}\");\n continue;\n }\n $discoveredData['prompts'][$name] = json_encode($prompt);\n }\n }\n\n foreach ($this->resourceTemplates as $uriTemplate => $template) {\n if (! $template->isManual) {\n if ($template->handler instanceof \\Closure) {\n $this->logger->warning(\"Skipping closure template from cache: {$uriTemplate}\");\n continue;\n }\n $discoveredData['resourceTemplates'][$uriTemplate] = json_encode($template);\n }\n }\n\n try {\n $success = $this->cache->set(self::DISCOVERED_ELEMENTS_CACHE_KEY, $discoveredData);\n\n if ($success) {\n $this->logger->debug('Registry elements saved to cache.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY]);\n } else {\n $this->logger->warning('Registry cache set operation returned false.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY]);\n }\n\n return $success;\n } catch (CacheInvalidArgumentException $e) {\n $this->logger->error('Invalid cache key or value during save.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY, 'exception' => $e]);\n\n return false;\n } catch (Throwable $e) {\n $this->logger->error('Unexpected error saving to cache.', ['key' => self::DISCOVERED_ELEMENTS_CACHE_KEY, 'exception' => $e]);\n\n return false;\n }\n }\n\n /** Checks if any elements (manual or discovered) are currently registered. */\n public function hasElements(): bool\n {\n return ! empty($this->tools)\n || ! empty($this->resources)\n || ! empty($this->prompts)\n || ! empty($this->resourceTemplates);\n }\n\n /**\n * Clear discovered elements from registry\n * \n * @param bool $includeCache Whether to clear the cache as well (default: true)\n */\n public function clear(bool $includeCache = true): void\n {\n if ($includeCache && $this->cache !== null) {\n try {\n $this->cache->delete(self::DISCOVERED_ELEMENTS_CACHE_KEY);\n $this->logger->debug('Registry cache cleared.');\n } catch (Throwable $e) {\n $this->logger->error('Error clearing registry cache.', ['exception' => $e]);\n }\n }\n\n $clearCount = 0;\n\n foreach ($this->tools as $name => $tool) {\n if (! $tool->isManual) {\n unset($this->tools[$name]);\n $clearCount++;\n }\n }\n foreach ($this->resources as $uri => $resource) {\n if (! $resource->isManual) {\n unset($this->resources[$uri]);\n $clearCount++;\n }\n }\n foreach ($this->prompts as $name => $prompt) {\n if (! $prompt->isManual) {\n unset($this->prompts[$name]);\n $clearCount++;\n }\n }\n foreach ($this->resourceTemplates as $uriTemplate => $template) {\n if (! $template->isManual) {\n unset($this->resourceTemplates[$uriTemplate]);\n $clearCount++;\n }\n }\n\n if ($clearCount > 0) {\n $this->logger->debug(\"Removed {$clearCount} discovered elements from internal registry.\");\n }\n }\n\n /** @return RegisteredTool|null */\n public function getTool(string $name): ?RegisteredTool\n {\n return $this->tools[$name] ?? null;\n }\n\n /** @return RegisteredResource|RegisteredResourceTemplate|null */\n public function getResource(string $uri, bool $includeTemplates = true): RegisteredResource|RegisteredResourceTemplate|null\n {\n $registration = $this->resources[$uri] ?? null;\n if ($registration) {\n return $registration;\n }\n\n if (! $includeTemplates) {\n return null;\n }\n\n foreach ($this->resourceTemplates as $template) {\n if ($template->matches($uri)) {\n return $template;\n }\n }\n\n $this->logger->debug('No resource matched URI.', ['uri' => $uri]);\n\n return null;\n }\n\n /** @return RegisteredResourceTemplate|null */\n public function getResourceTemplate(string $uriTemplate): ?RegisteredResourceTemplate\n {\n return $this->resourceTemplates[$uriTemplate] ?? null;\n }\n\n /** @return RegisteredPrompt|null */\n public function getPrompt(string $name): ?RegisteredPrompt\n {\n return $this->prompts[$name] ?? null;\n }\n\n /** @return array */\n public function getTools(): array\n {\n return array_map(fn($tool) => $tool->schema, $this->tools);\n }\n\n /** @return array */\n public function getResources(): array\n {\n return array_map(fn($resource) => $resource->schema, $this->resources);\n }\n\n /** @return array */\n public function getPrompts(): array\n {\n return array_map(fn($prompt) => $prompt->schema, $this->prompts);\n }\n\n /** @return array */\n public function getResourceTemplates(): array\n {\n return array_map(fn($template) => $template->schema, $this->resourceTemplates);\n }\n}\n"], ["/server/src/Utils/SchemaGenerator.php", "docBlockParser = $docBlockParser;\n }\n\n /**\n * Generates a JSON Schema object (as a PHP array) for a method's or function's parameters.\n */\n public function generate(\\ReflectionMethod|\\ReflectionFunction $reflection): array\n {\n $methodSchema = $this->extractMethodLevelSchema($reflection);\n\n if ($methodSchema && isset($methodSchema['definition'])) {\n return $methodSchema['definition'];\n }\n\n $parametersInfo = $this->parseParametersInfo($reflection);\n\n return $this->buildSchemaFromParameters($parametersInfo, $methodSchema);\n }\n\n /**\n * Extracts method-level or function-level Schema attribute.\n */\n private function extractMethodLevelSchema(\\ReflectionMethod|\\ReflectionFunction $reflection): ?array\n {\n $schemaAttrs = $reflection->getAttributes(Schema::class, \\ReflectionAttribute::IS_INSTANCEOF);\n if (empty($schemaAttrs)) {\n return null;\n }\n\n $schemaAttr = $schemaAttrs[0]->newInstance();\n return $schemaAttr->toArray();\n }\n\n /**\n * Extracts parameter-level Schema attribute.\n */\n private function extractParameterLevelSchema(ReflectionParameter $parameter): array\n {\n $schemaAttrs = $parameter->getAttributes(Schema::class, \\ReflectionAttribute::IS_INSTANCEOF);\n if (empty($schemaAttrs)) {\n return [];\n }\n\n $schemaAttr = $schemaAttrs[0]->newInstance();\n return $schemaAttr->toArray();\n }\n\n /**\n * Builds the final schema from parameter information and method-level schema.\n *\n * @param array\n * }> $parametersInfo\n *\n * @param array|null $methodSchema\n *\n * @return array\n */\n private function buildSchemaFromParameters(array $parametersInfo, ?array $methodSchema): array\n {\n $schema = [\n 'type' => 'object',\n 'properties' => [],\n 'required' => [],\n ];\n\n // Apply method-level schema as base\n if ($methodSchema) {\n $schema = array_merge($schema, $methodSchema);\n if (!isset($schema['type'])) {\n $schema['type'] = 'object';\n }\n if (!isset($schema['properties'])) {\n $schema['properties'] = [];\n }\n if (!isset($schema['required'])) {\n $schema['required'] = [];\n }\n }\n\n foreach ($parametersInfo as $paramInfo) {\n $paramName = $paramInfo['name'];\n\n $methodLevelParamSchema = $schema['properties'][$paramName] ?? null;\n\n $paramSchema = $this->buildParameterSchema($paramInfo, $methodLevelParamSchema);\n\n $schema['properties'][$paramName] = $paramSchema;\n\n if ($paramInfo['required'] && !in_array($paramName, $schema['required'])) {\n $schema['required'][] = $paramName;\n } elseif (!$paramInfo['required'] && ($key = array_search($paramName, $schema['required'])) !== false) {\n unset($schema['required'][$key]);\n $schema['required'] = array_values($schema['required']); // Re-index\n }\n }\n\n // Clean up empty properties\n if (empty($schema['properties'])) {\n $schema['properties'] = new stdClass();\n }\n if (empty($schema['required'])) {\n unset($schema['required']);\n }\n\n return $schema;\n }\n\n /**\n * Builds the final schema for a single parameter by merging all three levels.\n *\n * @param array{\n * name: string,\n * doc_block_tag: Param|null,\n * reflection_param: ReflectionParameter,\n * reflection_type_object: ReflectionType|null,\n * type_string: string,\n * description: string|null,\n * required: bool,\n * allows_null: bool,\n * default_value: mixed|null,\n * has_default: bool,\n * is_variadic: bool,\n * parameter_schema: array\n * } $paramInfo\n * @param array|null $methodLevelParamSchema\n */\n private function buildParameterSchema(array $paramInfo, ?array $methodLevelParamSchema = null): array\n {\n if ($paramInfo['is_variadic']) {\n return $this->buildVariadicParameterSchema($paramInfo);\n }\n\n $inferredSchema = $this->buildInferredParameterSchema($paramInfo);\n\n // Method-level takes precedence over inferred schema\n $mergedSchema = $inferredSchema;\n if ($methodLevelParamSchema) {\n $mergedSchema = $this->mergeSchemas($inferredSchema, $methodLevelParamSchema);\n }\n\n // Parameter-level takes highest precedence\n $parameterLevelSchema = $paramInfo['parameter_schema'];\n if (!empty($parameterLevelSchema)) {\n $mergedSchema = $this->mergeSchemas($mergedSchema, $parameterLevelSchema);\n }\n\n return $mergedSchema;\n }\n\n /**\n * Merge two schemas where the dominant schema takes precedence over the recessive one.\n *\n * @param array $recessiveSchema The schema with lower precedence\n * @param array $dominantSchema The schema with higher precedence\n */\n private function mergeSchemas(array $recessiveSchema, array $dominantSchema): array\n {\n $mergedSchema = array_merge($recessiveSchema, $dominantSchema);\n\n return $mergedSchema;\n }\n\n /**\n * Builds parameter schema from inferred type and docblock information only.\n * Returns empty array for variadic parameters (handled separately).\n */\n private function buildInferredParameterSchema(array $paramInfo): array\n {\n $paramSchema = [];\n\n // Variadic parameters are handled separately\n if ($paramInfo['is_variadic']) {\n return [];\n }\n\n // Infer JSON Schema types\n $jsonTypes = $this->inferParameterTypes($paramInfo);\n\n if (count($jsonTypes) === 1) {\n $paramSchema['type'] = $jsonTypes[0];\n } elseif (count($jsonTypes) > 1) {\n $paramSchema['type'] = $jsonTypes;\n }\n\n // Add description from docblock\n if ($paramInfo['description']) {\n $paramSchema['description'] = $paramInfo['description'];\n }\n\n // Add default value only if parameter actually has a default\n if ($paramInfo['has_default']) {\n $paramSchema['default'] = $paramInfo['default_value'];\n }\n\n // Handle enums\n $paramSchema = $this->applyEnumConstraints($paramSchema, $paramInfo);\n\n // Handle array items\n $paramSchema = $this->applyArrayConstraints($paramSchema, $paramInfo);\n\n return $paramSchema;\n }\n\n /**\n * Builds schema for variadic parameters.\n */\n private function buildVariadicParameterSchema(array $paramInfo): array\n {\n $paramSchema = ['type' => 'array'];\n\n // Apply parameter-level Schema attributes first\n if (!empty($paramInfo['parameter_schema'])) {\n $paramSchema = array_merge($paramSchema, $paramInfo['parameter_schema']);\n // Ensure type is always array for variadic\n $paramSchema['type'] = 'array';\n }\n\n if ($paramInfo['description']) {\n $paramSchema['description'] = $paramInfo['description'];\n }\n\n // If no items specified by Schema attribute, infer from type\n if (!isset($paramSchema['items'])) {\n $itemJsonTypes = $this->mapPhpTypeToJsonSchemaType($paramInfo['type_string']);\n $nonNullItemTypes = array_filter($itemJsonTypes, fn($t) => $t !== 'null');\n\n if (count($nonNullItemTypes) === 1) {\n $paramSchema['items'] = ['type' => $nonNullItemTypes[0]];\n }\n }\n\n return $paramSchema;\n }\n\n /**\n * Infers JSON Schema types for a parameter.\n */\n private function inferParameterTypes(array $paramInfo): array\n {\n $jsonTypes = $this->mapPhpTypeToJsonSchemaType($paramInfo['type_string']);\n\n if ($paramInfo['allows_null'] && strtolower($paramInfo['type_string']) !== 'mixed' && !in_array('null', $jsonTypes)) {\n $jsonTypes[] = 'null';\n }\n\n if (count($jsonTypes) > 1) {\n // Sort but ensure null comes first for consistency\n $nullIndex = array_search('null', $jsonTypes);\n if ($nullIndex !== false) {\n unset($jsonTypes[$nullIndex]);\n sort($jsonTypes);\n array_unshift($jsonTypes, 'null');\n } else {\n sort($jsonTypes);\n }\n }\n\n return $jsonTypes;\n }\n\n /**\n * Applies enum constraints to parameter schema.\n */\n private function applyEnumConstraints(array $paramSchema, array $paramInfo): array\n {\n $reflectionType = $paramInfo['reflection_type_object'];\n\n if (!($reflectionType instanceof ReflectionNamedType) || $reflectionType->isBuiltin() || !enum_exists($reflectionType->getName())) {\n return $paramSchema;\n }\n\n $enumClass = $reflectionType->getName();\n $enumReflection = new ReflectionEnum($enumClass);\n $backingTypeReflection = $enumReflection->getBackingType();\n\n if ($enumReflection->isBacked() && $backingTypeReflection instanceof ReflectionNamedType) {\n $paramSchema['enum'] = array_column($enumClass::cases(), 'value');\n $jsonBackingType = match ($backingTypeReflection->getName()) {\n 'int' => 'integer',\n 'string' => 'string',\n default => null,\n };\n\n if ($jsonBackingType) {\n if (isset($paramSchema['type']) && is_array($paramSchema['type']) && in_array('null', $paramSchema['type'])) {\n $paramSchema['type'] = ['null', $jsonBackingType];\n } else {\n $paramSchema['type'] = $jsonBackingType;\n }\n }\n } else {\n // Non-backed enum - use names as enum values\n $paramSchema['enum'] = array_column($enumClass::cases(), 'name');\n if (isset($paramSchema['type']) && is_array($paramSchema['type']) && in_array('null', $paramSchema['type'])) {\n $paramSchema['type'] = ['null', 'string'];\n } else {\n $paramSchema['type'] = 'string';\n }\n }\n\n return $paramSchema;\n }\n\n /**\n * Applies array-specific constraints to parameter schema.\n */\n private function applyArrayConstraints(array $paramSchema, array $paramInfo): array\n {\n if (!isset($paramSchema['type'])) {\n return $paramSchema;\n }\n\n $typeString = $paramInfo['type_string'];\n $allowsNull = $paramInfo['allows_null'];\n\n // Handle object-like arrays using array{} syntax\n if (preg_match('/^array\\s*{/i', $typeString)) {\n $objectSchema = $this->inferArrayItemsType($typeString);\n if (is_array($objectSchema) && isset($objectSchema['properties'])) {\n $paramSchema = array_merge($paramSchema, $objectSchema);\n $paramSchema['type'] = $allowsNull ? ['object', 'null'] : 'object';\n }\n }\n // Handle regular arrays\n elseif (in_array('array', $this->mapPhpTypeToJsonSchemaType($typeString))) {\n $itemsType = $this->inferArrayItemsType($typeString);\n if ($itemsType !== 'any') {\n if (is_string($itemsType)) {\n $paramSchema['items'] = ['type' => $itemsType];\n } else {\n if (!isset($itemsType['type']) && isset($itemsType['properties'])) {\n $itemsType = array_merge(['type' => 'object'], $itemsType);\n }\n $paramSchema['items'] = $itemsType;\n }\n }\n\n if ($allowsNull) {\n $paramSchema['type'] = ['array', 'null'];\n sort($paramSchema['type']);\n } else {\n $paramSchema['type'] = 'array';\n }\n }\n\n return $paramSchema;\n }\n\n /**\n * Parses detailed information about a method's parameters.\n *\n * @return array\n * }>\n */\n private function parseParametersInfo(\\ReflectionMethod|\\ReflectionFunction $reflection): array\n {\n $docComment = $reflection->getDocComment() ?: null;\n $docBlock = $this->docBlockParser->parseDocBlock($docComment);\n $paramTags = $this->docBlockParser->getParamTags($docBlock);\n $parametersInfo = [];\n\n foreach ($reflection->getParameters() as $rp) {\n $paramName = $rp->getName();\n $paramTag = $paramTags['$' . $paramName] ?? null;\n\n $reflectionType = $rp->getType();\n\n if ($reflectionType instanceof ReflectionNamedType && $reflectionType?->getName() === Context::class) {\n continue;\n }\n\n $typeString = $this->getParameterTypeString($rp, $paramTag);\n $description = $this->docBlockParser->getParamDescription($paramTag);\n $hasDefault = $rp->isDefaultValueAvailable();\n $defaultValue = $hasDefault ? $rp->getDefaultValue() : null;\n $isVariadic = $rp->isVariadic();\n\n $parameterSchema = $this->extractParameterLevelSchema($rp);\n\n if ($defaultValue instanceof \\BackedEnum) {\n $defaultValue = $defaultValue->value;\n }\n\n if ($defaultValue instanceof \\UnitEnum) {\n $defaultValue = $defaultValue->name;\n }\n\n $allowsNull = false;\n if ($reflectionType && $reflectionType->allowsNull()) {\n $allowsNull = true;\n } elseif ($hasDefault && $defaultValue === null) {\n $allowsNull = true;\n } elseif (str_contains($typeString, 'null') || strtolower($typeString) === 'mixed') {\n $allowsNull = true;\n }\n\n $parametersInfo[] = [\n 'name' => $paramName,\n 'doc_block_tag' => $paramTag,\n 'reflection_param' => $rp,\n 'reflection_type_object' => $reflectionType,\n 'type_string' => $typeString,\n 'description' => $description,\n 'required' => !$rp->isOptional(),\n 'allows_null' => $allowsNull,\n 'default_value' => $defaultValue,\n 'has_default' => $hasDefault,\n 'is_variadic' => $isVariadic,\n 'parameter_schema' => $parameterSchema,\n ];\n }\n\n return $parametersInfo;\n }\n\n /**\n * Determines the type string for a parameter, prioritizing DocBlock.\n */\n private function getParameterTypeString(ReflectionParameter $rp, ?Param $paramTag): string\n {\n $docBlockType = $this->docBlockParser->getParamTypeString($paramTag);\n $isDocBlockTypeGeneric = false;\n\n if ($docBlockType !== null) {\n if (in_array(strtolower($docBlockType), ['mixed', 'unknown', ''])) {\n $isDocBlockTypeGeneric = true;\n }\n } else {\n $isDocBlockTypeGeneric = true; // No tag or no type in tag implies generic\n }\n\n $reflectionType = $rp->getType();\n $reflectionTypeString = null;\n if ($reflectionType) {\n $reflectionTypeString = $this->getTypeStringFromReflection($reflectionType, $rp->allowsNull());\n }\n\n // Prioritize Reflection if DocBlock type is generic AND Reflection provides a more specific type\n if ($isDocBlockTypeGeneric && $reflectionTypeString !== null && $reflectionTypeString !== 'mixed') {\n return $reflectionTypeString;\n }\n\n // Otherwise, use the DocBlock type if it was valid and non-generic\n if ($docBlockType !== null && !$isDocBlockTypeGeneric) {\n // Consider if DocBlock adds nullability missing from reflection\n if (stripos($docBlockType, 'null') !== false && $reflectionTypeString && stripos($reflectionTypeString, 'null') === false && !str_ends_with($reflectionTypeString, '|null')) {\n // If reflection didn't capture null, but docblock did, append |null (if not already mixed)\n if ($reflectionTypeString !== 'mixed') {\n return $reflectionTypeString . '|null';\n }\n }\n\n return $docBlockType;\n }\n\n // Fallback to Reflection type even if it was generic ('mixed')\n if ($reflectionTypeString !== null) {\n return $reflectionTypeString;\n }\n\n // Default to 'mixed' if nothing else found\n return 'mixed';\n }\n\n /**\n * Converts a ReflectionType object into a type string representation.\n */\n private function getTypeStringFromReflection(?ReflectionType $type, bool $nativeAllowsNull): string\n {\n if ($type === null) {\n return 'mixed';\n }\n\n $types = [];\n if ($type instanceof ReflectionUnionType) {\n foreach ($type->getTypes() as $innerType) {\n $types[] = $this->getTypeStringFromReflection($innerType, $innerType->allowsNull());\n }\n if ($nativeAllowsNull) {\n $types = array_filter($types, fn($t) => strtolower($t) !== 'null');\n }\n $typeString = implode('|', array_unique(array_filter($types)));\n } elseif ($type instanceof ReflectionIntersectionType) {\n foreach ($type->getTypes() as $innerType) {\n $types[] = $this->getTypeStringFromReflection($innerType, false);\n }\n $typeString = implode('&', array_unique(array_filter($types)));\n } elseif ($type instanceof ReflectionNamedType) {\n $typeString = $type->getName();\n } else {\n return 'mixed';\n }\n\n $typeString = match (strtolower($typeString)) {\n 'bool' => 'boolean',\n 'int' => 'integer',\n 'float', 'double' => 'number',\n 'str' => 'string',\n default => $typeString,\n };\n\n $isNullable = $nativeAllowsNull;\n if ($type instanceof ReflectionNamedType && $type->getName() === 'mixed') {\n $isNullable = true;\n }\n\n if ($type instanceof ReflectionUnionType && !$nativeAllowsNull) {\n foreach ($type->getTypes() as $innerType) {\n if ($innerType instanceof ReflectionNamedType && strtolower($innerType->getName()) === 'null') {\n $isNullable = true;\n break;\n }\n }\n }\n\n if ($isNullable && $typeString !== 'mixed' && stripos($typeString, 'null') === false) {\n if (!str_ends_with($typeString, '|null') && !str_ends_with($typeString, '&null')) {\n $typeString .= '|null';\n }\n }\n\n // Remove leading backslash from class names, but handle built-ins like 'int' or unions like 'int|string'\n if (str_contains($typeString, '\\\\')) {\n $parts = preg_split('/([|&])/', $typeString, -1, PREG_SPLIT_DELIM_CAPTURE);\n $processedParts = array_map(fn($part) => str_starts_with($part, '\\\\') ? ltrim($part, '\\\\') : $part, $parts);\n $typeString = implode('', $processedParts);\n }\n\n return $typeString ?: 'mixed';\n }\n\n /**\n * Maps a PHP type string (potentially a union) to an array of JSON Schema type names.\n */\n private function mapPhpTypeToJsonSchemaType(string $phpTypeString): array\n {\n $normalizedType = strtolower(trim($phpTypeString));\n\n // PRIORITY 1: Check for array{} syntax which should be treated as object\n if (preg_match('/^array\\s*{/i', $normalizedType)) {\n return ['object'];\n }\n\n // PRIORITY 2: Check for array syntax first (T[] or generics)\n if (\n str_contains($normalizedType, '[]') ||\n preg_match('/^(array|list|iterable|collection)mapPhpTypeToJsonSchemaType(trim($type));\n $jsonTypes = array_merge($jsonTypes, $mapped);\n }\n\n return array_values(array_unique($jsonTypes));\n }\n\n // PRIORITY 4: Handle simple built-in types\n return match ($normalizedType) {\n 'string', 'scalar' => ['string'],\n '?string' => ['null', 'string'],\n 'int', 'integer' => ['integer'],\n '?int', '?integer' => ['null', 'integer'],\n 'float', 'double', 'number' => ['number'],\n '?float', '?double', '?number' => ['null', 'number'],\n 'bool', 'boolean' => ['boolean'],\n '?bool', '?boolean' => ['null', 'boolean'],\n 'array' => ['array'],\n '?array' => ['null', 'array'],\n 'object', 'stdclass' => ['object'],\n '?object', '?stdclass' => ['null', 'object'],\n 'null' => ['null'],\n 'resource', 'callable' => ['object'],\n 'mixed' => [],\n 'void', 'never' => [],\n default => ['object'],\n };\n }\n\n /**\n * Infers the 'items' schema type for an array based on DocBlock type hints.\n */\n private function inferArrayItemsType(string $phpTypeString): string|array\n {\n $normalizedType = trim($phpTypeString);\n\n // Case 1: Simple T[] syntax (e.g., string[], int[], bool[], etc.)\n if (preg_match('/^(\\\\??)([\\w\\\\\\\\]+)\\\\s*\\\\[\\\\]$/i', $normalizedType, $matches)) {\n $itemType = strtolower($matches[2]);\n return $this->mapSimpleTypeToJsonSchema($itemType);\n }\n\n // Case 2: Generic array syntax (e.g., array, array, etc.)\n if (preg_match('/^(\\\\??)array\\s*<\\s*([\\w\\\\\\\\|]+)\\s*>$/i', $normalizedType, $matches)) {\n $itemType = strtolower($matches[2]);\n return $this->mapSimpleTypeToJsonSchema($itemType);\n }\n\n // Case 3: Nested array> syntax or T[][] syntax\n if (\n preg_match('/^(\\\\??)array\\s*<\\s*array\\s*<\\s*([\\w\\\\\\\\|]+)\\s*>\\s*>$/i', $normalizedType, $matches) ||\n preg_match('/^(\\\\??)([\\w\\\\\\\\]+)\\s*\\[\\]\\[\\]$/i', $normalizedType, $matches)\n ) {\n $innerType = $this->mapSimpleTypeToJsonSchema(isset($matches[2]) ? strtolower($matches[2]) : 'any');\n // Return a schema for array with items being arrays\n return [\n 'type' => 'array',\n 'items' => [\n 'type' => $innerType\n ]\n ];\n }\n\n // Case 4: Object-like array syntax (e.g., array{name: string, age: int})\n if (preg_match('/^(\\\\??)array\\s*\\{(.+)\\}$/is', $normalizedType, $matches)) {\n return $this->parseObjectLikeArray($matches[2]);\n }\n\n return 'any';\n }\n\n /**\n * Parses object-like array syntax into a JSON Schema object\n */\n private function parseObjectLikeArray(string $propertiesStr): array\n {\n $properties = [];\n $required = [];\n\n // Parse properties from the string, handling nested structures\n $depth = 0;\n $buffer = '';\n\n for ($i = 0; $i < strlen($propertiesStr); $i++) {\n $char = $propertiesStr[$i];\n\n // Track nested braces\n if ($char === '{') {\n $depth++;\n $buffer .= $char;\n } elseif ($char === '}') {\n $depth--;\n $buffer .= $char;\n }\n // Property separator (comma)\n elseif ($char === ',' && $depth === 0) {\n // Process the completed property\n $this->parsePropertyDefinition(trim($buffer), $properties, $required);\n $buffer = '';\n } else {\n $buffer .= $char;\n }\n }\n\n // Process the last property\n if (!empty($buffer)) {\n $this->parsePropertyDefinition(trim($buffer), $properties, $required);\n }\n\n if (!empty($properties)) {\n return [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $required\n ];\n }\n\n return ['type' => 'object'];\n }\n\n /**\n * Parses a single property definition from an object-like array syntax\n */\n private function parsePropertyDefinition(string $propDefinition, array &$properties, array &$required): void\n {\n // Match property name and type\n if (preg_match('/^([a-zA-Z_\\x80-\\xff][a-zA-Z0-9_\\x80-\\xff]*)\\s*:\\s*(.+)$/i', $propDefinition, $matches)) {\n $propName = $matches[1];\n $propType = trim($matches[2]);\n\n // Add to required properties\n $required[] = $propName;\n\n // Check for nested array{} syntax\n if (preg_match('/^array\\s*\\{(.+)\\}$/is', $propType, $nestedMatches)) {\n $nestedSchema = $this->parseObjectLikeArray($nestedMatches[1]);\n $properties[$propName] = $nestedSchema;\n }\n // Check for array or T[] syntax\n elseif (\n preg_match('/^array\\s*<\\s*([\\w\\\\\\\\|]+)\\s*>$/i', $propType, $arrayMatches) ||\n preg_match('/^([\\w\\\\\\\\]+)\\s*\\[\\]$/i', $propType, $arrayMatches)\n ) {\n $itemType = $arrayMatches[1] ?? 'any';\n $properties[$propName] = [\n 'type' => 'array',\n 'items' => [\n 'type' => $this->mapSimpleTypeToJsonSchema($itemType)\n ]\n ];\n }\n // Simple type\n else {\n $properties[$propName] = ['type' => $this->mapSimpleTypeToJsonSchema($propType)];\n }\n }\n }\n\n /**\n * Helper method to map basic PHP types to JSON Schema types\n */\n private function mapSimpleTypeToJsonSchema(string $type): string\n {\n return match (strtolower($type)) {\n 'string' => 'string',\n 'int', 'integer' => 'integer',\n 'bool', 'boolean' => 'boolean',\n 'float', 'double', 'number' => 'number',\n 'array' => 'array',\n 'object', 'stdclass' => 'object',\n default => in_array(strtolower($type), ['datetime', 'datetimeinterface']) ? 'string' : 'object',\n };\n }\n}\n"], ["/server/src/Transports/StreamableHttpServerTransport.php", "\n */\n private array $pendingRequests = [];\n\n /**\n * Stores active SSE streams.\n * Key: streamId\n * Value: ['stream' => ThroughStream, 'sessionId' => string, 'context' => array]\n * @var array\n */\n private array $activeSseStreams = [];\n\n private ?ThroughStream $getStream = null;\n\n /**\n * @param bool $enableJsonResponse If true, the server will return JSON responses instead of starting an SSE stream.\n * This can be useful for simple request/response scenarios without streaming.\n */\n public function __construct(\n private readonly string $host = '127.0.0.1',\n private readonly int $port = 8080,\n private string $mcpPath = '/mcp',\n private ?array $sslContext = null,\n private readonly bool $enableJsonResponse = true,\n private readonly bool $stateless = false,\n ?EventStoreInterface $eventStore = null\n ) {\n $this->logger = new NullLogger();\n $this->loop = Loop::get();\n $this->mcpPath = '/' . trim($mcpPath, '/');\n $this->eventStore = $eventStore;\n }\n\n protected function generateId(): string\n {\n return bin2hex(random_bytes(16)); // 32 hex characters\n }\n\n public function setLogger(LoggerInterface $logger): void\n {\n $this->logger = $logger;\n }\n\n public function setLoop(LoopInterface $loop): void\n {\n $this->loop = $loop;\n }\n\n public function listen(): void\n {\n if ($this->listening) {\n throw new TransportException('StreamableHttp transport is already listening.');\n }\n\n if ($this->closing) {\n throw new TransportException('Cannot listen, transport is closing/closed.');\n }\n\n $listenAddress = \"{$this->host}:{$this->port}\";\n $protocol = $this->sslContext ? 'https' : 'http';\n\n try {\n $this->socket = new SocketServer(\n $listenAddress,\n $this->sslContext ?? [],\n $this->loop\n );\n\n $this->http = new HttpServer($this->loop, $this->createRequestHandler());\n $this->http->listen($this->socket);\n\n $this->socket->on('error', function (Throwable $error) {\n $this->logger->error('Socket server error (StreamableHttp).', ['error' => $error->getMessage()]);\n $this->emit('error', [new TransportException(\"Socket server error: {$error->getMessage()}\", 0, $error)]);\n $this->close();\n });\n\n $this->logger->info(\"Server is up and listening on {$protocol}://{$listenAddress} 🚀\");\n $this->logger->info(\"MCP Endpoint: {$protocol}://{$listenAddress}{$this->mcpPath}\");\n\n $this->listening = true;\n $this->closing = false;\n $this->emit('ready');\n } catch (Throwable $e) {\n $this->logger->error(\"Failed to start StreamableHttp listener on {$listenAddress}\", ['exception' => $e]);\n throw new TransportException(\"Failed to start StreamableHttp listener on {$listenAddress}: {$e->getMessage()}\", 0, $e);\n }\n }\n\n private function createRequestHandler(): callable\n {\n return function (ServerRequestInterface $request) {\n $path = $request->getUri()->getPath();\n $method = $request->getMethod();\n\n $this->logger->debug(\"Request received\", ['method' => $method, 'path' => $path, 'target' => $this->mcpPath]);\n\n if ($path !== $this->mcpPath) {\n $error = Error::forInvalidRequest(\"Not found: {$path}\");\n return new HttpResponse(404, ['Content-Type' => 'application/json'], json_encode($error));\n }\n\n $corsHeaders = [\n 'Access-Control-Allow-Origin' => '*',\n 'Access-Control-Allow-Methods' => 'GET, POST, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers' => 'Content-Type, Mcp-Session-Id, Last-Event-ID, Authorization',\n ];\n\n if ($method === 'OPTIONS') {\n return new HttpResponse(204, $corsHeaders);\n }\n\n $addCors = function (HttpResponse $r) use ($corsHeaders) {\n foreach ($corsHeaders as $key => $value) {\n $r = $r->withAddedHeader($key, $value);\n }\n return $r;\n };\n\n try {\n return match ($method) {\n 'GET' => $this->handleGetRequest($request)->then($addCors, fn($e) => $addCors($this->handleRequestError($e, $request))),\n 'POST' => $this->handlePostRequest($request)->then($addCors, fn($e) => $addCors($this->handleRequestError($e, $request))),\n 'DELETE' => $this->handleDeleteRequest($request)->then($addCors, fn($e) => $addCors($this->handleRequestError($e, $request))),\n default => $addCors($this->handleUnsupportedRequest($request)),\n };\n } catch (Throwable $e) {\n return $addCors($this->handleRequestError($e, $request));\n }\n };\n }\n\n private function handleGetRequest(ServerRequestInterface $request): PromiseInterface\n {\n if ($this->stateless) {\n $error = Error::forInvalidRequest(\"GET requests (SSE streaming) are not supported in stateless mode.\");\n return resolve(new HttpResponse(405, ['Content-Type' => 'application/json'], json_encode($error)));\n }\n\n $acceptHeader = $request->getHeaderLine('Accept');\n if (!str_contains($acceptHeader, 'text/event-stream')) {\n $error = Error::forInvalidRequest(\"Not Acceptable: Client must accept text/event-stream for GET requests.\");\n return resolve(new HttpResponse(406, ['Content-Type' => 'application/json'], json_encode($error)));\n }\n\n $sessionId = $request->getHeaderLine('Mcp-Session-Id');\n if (empty($sessionId)) {\n $this->logger->warning(\"GET request without Mcp-Session-Id.\");\n $error = Error::forInvalidRequest(\"Mcp-Session-Id header required for GET requests.\");\n return resolve(new HttpResponse(400, ['Content-Type' => 'application/json'], json_encode($error)));\n }\n\n $this->getStream = new ThroughStream();\n\n $this->getStream->on('close', function () use ($sessionId) {\n $this->logger->debug(\"GET SSE stream closed.\", ['sessionId' => $sessionId]);\n $this->getStream = null;\n });\n\n $this->getStream->on('error', function (Throwable $e) use ($sessionId) {\n $this->logger->error(\"GET SSE stream error.\", ['sessionId' => $sessionId, 'error' => $e->getMessage()]);\n $this->getStream = null;\n });\n\n $headers = [\n 'Content-Type' => 'text/event-stream',\n 'Cache-Control' => 'no-cache',\n 'Connection' => 'keep-alive',\n 'X-Accel-Buffering' => 'no',\n ];\n\n $response = new HttpResponse(200, $headers, $this->getStream);\n\n if ($this->eventStore) {\n $lastEventId = $request->getHeaderLine('Last-Event-ID');\n $this->replayEvents($lastEventId, $this->getStream, $sessionId);\n }\n\n return resolve($response);\n }\n\n private function handlePostRequest(ServerRequestInterface $request): PromiseInterface\n {\n $deferred = new Deferred();\n\n $acceptHeader = $request->getHeaderLine('Accept');\n if (!str_contains($acceptHeader, 'application/json') && !str_contains($acceptHeader, 'text/event-stream')) {\n $error = Error::forInvalidRequest(\"Not Acceptable: Client must accept both application/json or text/event-stream\");\n $deferred->resolve(new HttpResponse(406, ['Content-Type' => 'application/json'], json_encode($error)));\n return $deferred->promise();\n }\n\n if (!str_contains($request->getHeaderLine('Content-Type'), 'application/json')) {\n $error = Error::forInvalidRequest(\"Unsupported Media Type: Content-Type must be application/json\");\n $deferred->resolve(new HttpResponse(415, ['Content-Type' => 'application/json'], json_encode($error)));\n return $deferred->promise();\n }\n\n $body = $request->getBody()->getContents();\n\n if (empty($body)) {\n $this->logger->warning(\"Received empty POST body\");\n $error = Error::forInvalidRequest(\"Empty request body.\");\n $deferred->resolve(new HttpResponse(400, ['Content-Type' => 'application/json'], json_encode($error)));\n return $deferred->promise();\n }\n\n try {\n $message = Parser::parse($body);\n } catch (Throwable $e) {\n $this->logger->error(\"Failed to parse MCP message from POST body\", ['error' => $e->getMessage()]);\n $error = Error::forParseError(\"Invalid JSON: \" . $e->getMessage());\n $deferred->resolve(new HttpResponse(400, ['Content-Type' => 'application/json'], json_encode($error)));\n return $deferred->promise();\n }\n\n $isInitializeRequest = ($message instanceof Request && $message->method === 'initialize');\n $sessionId = null;\n\n if ($this->stateless) {\n $sessionId = $this->generateId();\n $this->emit('client_connected', [$sessionId]);\n } else {\n if ($isInitializeRequest) {\n if ($request->hasHeader('Mcp-Session-Id')) {\n $this->logger->warning(\"Client sent Mcp-Session-Id with InitializeRequest. Ignoring.\", ['clientSentId' => $request->getHeaderLine('Mcp-Session-Id')]);\n $error = Error::forInvalidRequest(\"Invalid request: Session already initialized. Mcp-Session-Id header not allowed with InitializeRequest.\", $message->getId());\n $deferred->resolve(new HttpResponse(400, ['Content-Type' => 'application/json'], json_encode($error)));\n return $deferred->promise();\n }\n\n $sessionId = $this->generateId();\n $this->emit('client_connected', [$sessionId]);\n } else {\n $sessionId = $request->getHeaderLine('Mcp-Session-Id');\n\n if (empty($sessionId)) {\n $this->logger->warning(\"POST request without Mcp-Session-Id.\");\n $error = Error::forInvalidRequest(\"Mcp-Session-Id header required for POST requests.\", $message->getId());\n $deferred->resolve(new HttpResponse(400, ['Content-Type' => 'application/json'], json_encode($error)));\n return $deferred->promise();\n }\n }\n }\n\n $context = [\n 'is_initialize_request' => $isInitializeRequest,\n ];\n\n $nRequests = match (true) {\n $message instanceof Request => 1,\n $message instanceof BatchRequest => $message->nRequests(),\n default => 0,\n };\n\n if ($nRequests === 0) {\n $deferred->resolve(new HttpResponse(202));\n $context['type'] = 'post_202_sent';\n } else {\n if ($this->enableJsonResponse) {\n $pendingRequestId = $this->generateId();\n $this->pendingRequests[$pendingRequestId] = $deferred;\n\n $timeoutTimer = $this->loop->addTimer(30, function () use ($pendingRequestId, $sessionId) {\n if (isset($this->pendingRequests[$pendingRequestId])) {\n $deferred = $this->pendingRequests[$pendingRequestId];\n unset($this->pendingRequests[$pendingRequestId]);\n $this->logger->warning(\"Timeout waiting for direct JSON response processing.\", ['pending_request_id' => $pendingRequestId, 'session_id' => $sessionId]);\n $errorResponse = McpServerException::internalError(\"Request processing timed out.\")->toJsonRpcError($pendingRequestId);\n $deferred->resolve(new HttpResponse(500, ['Content-Type' => 'application/json'], json_encode($errorResponse->toArray())));\n }\n });\n\n $this->pendingRequests[$pendingRequestId]->promise()->finally(function () use ($timeoutTimer) {\n $this->loop->cancelTimer($timeoutTimer);\n });\n\n $context['type'] = 'post_json';\n $context['pending_request_id'] = $pendingRequestId;\n } else {\n $streamId = $this->generateId();\n $sseStream = new ThroughStream();\n $this->activeSseStreams[$streamId] = [\n 'stream' => $sseStream,\n 'sessionId' => $sessionId,\n 'context' => ['nRequests' => $nRequests, 'nResponses' => 0]\n ];\n\n $sseStream->on('close', function () use ($streamId) {\n $this->logger->info(\"POST SSE stream closed by client/server.\", ['streamId' => $streamId, 'sessionId' => $this->activeSseStreams[$streamId]['sessionId']]);\n unset($this->activeSseStreams[$streamId]);\n });\n $sseStream->on('error', function (Throwable $e) use ($streamId) {\n $this->logger->error(\"POST SSE stream error.\", ['streamId' => $streamId, 'sessionId' => $this->activeSseStreams[$streamId]['sessionId'], 'error' => $e->getMessage()]);\n unset($this->activeSseStreams[$streamId]);\n });\n\n $headers = [\n 'Content-Type' => 'text/event-stream',\n 'Cache-Control' => 'no-cache',\n 'Connection' => 'keep-alive',\n 'X-Accel-Buffering' => 'no',\n ];\n\n if (!empty($sessionId) && !$this->stateless) {\n $headers['Mcp-Session-Id'] = $sessionId;\n }\n\n $deferred->resolve(new HttpResponse(200, $headers, $sseStream));\n $context['type'] = 'post_sse';\n $context['streamId'] = $streamId;\n $context['nRequests'] = $nRequests;\n }\n }\n\n $context['stateless'] = $this->stateless;\n $context['request'] = $request;\n\n $this->loop->futureTick(function () use ($message, $sessionId, $context) {\n $this->emit('message', [$message, $sessionId, $context]);\n });\n\n return $deferred->promise();\n }\n\n private function handleDeleteRequest(ServerRequestInterface $request): PromiseInterface\n {\n if ($this->stateless) {\n return resolve(new HttpResponse(204));\n }\n\n $sessionId = $request->getHeaderLine('Mcp-Session-Id');\n if (empty($sessionId)) {\n $this->logger->warning(\"DELETE request without Mcp-Session-Id.\");\n $error = Error::forInvalidRequest(\"Mcp-Session-Id header required for DELETE.\");\n return resolve(new HttpResponse(400, ['Content-Type' => 'application/json'], json_encode($error)));\n }\n\n $streamsToClose = [];\n foreach ($this->activeSseStreams as $streamId => $streamInfo) {\n if ($streamInfo['sessionId'] === $sessionId) {\n $streamsToClose[] = $streamId;\n }\n }\n\n foreach ($streamsToClose as $streamId) {\n $this->activeSseStreams[$streamId]['stream']->end();\n unset($this->activeSseStreams[$streamId]);\n }\n\n if ($this->getStream !== null) {\n $this->getStream->end();\n $this->getStream = null;\n }\n\n $this->emit('client_disconnected', [$sessionId, 'Session terminated by DELETE request']);\n\n return resolve(new HttpResponse(204));\n }\n\n private function handleUnsupportedRequest(ServerRequestInterface $request): HttpResponse\n {\n $error = Error::forInvalidRequest(\"Method not allowed: {$request->getMethod()}\");\n $headers = [\n 'Content-Type' => 'application/json',\n 'Allow' => 'GET, POST, DELETE, OPTIONS',\n ];\n return new HttpResponse(405, $headers, json_encode($error));\n }\n\n private function handleRequestError(Throwable $e, ServerRequestInterface $request): HttpResponse\n {\n $this->logger->error(\"Error processing HTTP request\", [\n 'method' => $request->getMethod(),\n 'path' => $request->getUri()->getPath(),\n 'exception' => $e->getMessage()\n ]);\n\n if ($e instanceof TransportException) {\n $error = Error::forInternalError(\"Transport Error: \" . $e->getMessage());\n return new HttpResponse(500, ['Content-Type' => 'application/json'], json_encode($error));\n }\n\n $error = Error::forInternalError(\"Internal Server Error during HTTP request processing.\");\n return new HttpResponse(500, ['Content-Type' => 'application/json'], json_encode($error));\n }\n\n public function sendMessage(Message $message, string $sessionId, array $context = []): PromiseInterface\n {\n if ($this->closing) {\n return reject(new TransportException('Transport is closing.'));\n }\n\n $isInitializeResponse = ($context['is_initialize_request'] ?? false) && ($message instanceof Response);\n\n switch ($context['type'] ?? null) {\n case 'post_202_sent':\n return resolve(null);\n\n case 'post_sse':\n $streamId = $context['streamId'];\n if (!isset($this->activeSseStreams[$streamId])) {\n $this->logger->error(\"SSE stream for POST not found.\", ['streamId' => $streamId, 'sessionId' => $sessionId]);\n return reject(new TransportException(\"SSE stream {$streamId} not found for POST response.\"));\n }\n\n $stream = $this->activeSseStreams[$streamId]['stream'];\n if (!$stream->isWritable()) {\n $this->logger->warning(\"SSE stream for POST is not writable.\", ['streamId' => $streamId, 'sessionId' => $sessionId]);\n return reject(new TransportException(\"SSE stream {$streamId} for POST is not writable.\"));\n }\n\n $sentCountThisCall = 0;\n\n if ($message instanceof Response || $message instanceof Error) {\n $json = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);\n $eventId = $this->eventStore ? $this->eventStore->storeEvent($streamId, $json) : null;\n $this->sendSseEventToStream($stream, $json, $eventId);\n $sentCountThisCall = 1;\n } elseif ($message instanceof BatchResponse) {\n foreach ($message->getAll() as $singleResponse) {\n $json = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);\n $eventId = $this->eventStore ? $this->eventStore->storeEvent($streamId, $json) : null;\n $this->sendSseEventToStream($stream, $json, $eventId);\n $sentCountThisCall++;\n }\n }\n\n if (isset($this->activeSseStreams[$streamId]['context'])) {\n $this->activeSseStreams[$streamId]['context']['nResponses'] += $sentCountThisCall;\n if ($this->activeSseStreams[$streamId]['context']['nResponses'] >= $this->activeSseStreams[$streamId]['context']['nRequests']) {\n $this->logger->info(\"All expected responses sent for POST SSE stream. Closing.\", ['streamId' => $streamId, 'sessionId' => $sessionId]);\n $stream->end(); // Will trigger 'close' event.\n\n if ($context['stateless'] ?? false) {\n $this->loop->futureTick(function () use ($sessionId) {\n $this->emit('client_disconnected', [$sessionId, 'Stateless request completed']);\n });\n }\n }\n }\n\n return resolve(null);\n\n case 'post_json':\n $pendingRequestId = $context['pending_request_id'];\n if (!isset($this->pendingRequests[$pendingRequestId])) {\n $this->logger->error(\"Pending direct JSON request not found.\", ['pending_request_id' => $pendingRequestId, 'session_id' => $sessionId]);\n return reject(new TransportException(\"Pending request {$pendingRequestId} not found.\"));\n }\n\n $deferred = $this->pendingRequests[$pendingRequestId];\n unset($this->pendingRequests[$pendingRequestId]);\n\n $responseBody = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);\n $headers = ['Content-Type' => 'application/json'];\n if ($isInitializeResponse && !$this->stateless) {\n $headers['Mcp-Session-Id'] = $sessionId;\n }\n\n $statusCode = $context['status_code'] ?? 200;\n $deferred->resolve(new HttpResponse($statusCode, $headers, $responseBody . \"\\n\"));\n\n if ($context['stateless'] ?? false) {\n $this->loop->futureTick(function () use ($sessionId) {\n $this->emit('client_disconnected', [$sessionId, 'Stateless request completed']);\n });\n }\n\n return resolve(null);\n\n default:\n if ($this->getStream === null) {\n $this->logger->error(\"GET SSE stream not found.\", ['sessionId' => $sessionId]);\n return reject(new TransportException(\"GET SSE stream not found.\"));\n }\n\n if (!$this->getStream->isWritable()) {\n $this->logger->warning(\"GET SSE stream is not writable.\", ['sessionId' => $sessionId]);\n return reject(new TransportException(\"GET SSE stream not writable.\"));\n }\n if ($message instanceof Response || $message instanceof Error) {\n $json = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);\n $eventId = $this->eventStore ? $this->eventStore->storeEvent('GET_STREAM', $json) : null;\n $this->sendSseEventToStream($this->getStream, $json, $eventId);\n } elseif ($message instanceof BatchResponse) {\n foreach ($message->getAll() as $singleResponse) {\n $json = json_encode($singleResponse, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);\n $eventId = $this->eventStore ? $this->eventStore->storeEvent('GET_STREAM', $json) : null;\n $this->sendSseEventToStream($this->getStream, $json, $eventId);\n }\n }\n return resolve(null);\n }\n }\n\n private function replayEvents(string $lastEventId, ThroughStream $sseStream, string $sessionId): void\n {\n if (empty($lastEventId)) {\n return;\n }\n\n try {\n $this->eventStore->replayEventsAfter(\n $lastEventId,\n function (string $replayedEventId, string $json) use ($sseStream) {\n $this->logger->debug(\"Replaying event\", ['replayedEventId' => $replayedEventId]);\n $this->sendSseEventToStream($sseStream, $json, $replayedEventId);\n }\n );\n } catch (Throwable $e) {\n $this->logger->error(\"Error during event replay.\", ['sessionId' => $sessionId, 'exception' => $e]);\n }\n }\n\n private function sendSseEventToStream(ThroughStream $stream, string $data, ?string $eventId = null): bool\n {\n if (! $stream->isWritable()) {\n return false;\n }\n\n $frame = \"event: message\\n\";\n if ($eventId !== null) {\n $frame .= \"id: {$eventId}\\n\";\n }\n\n $lines = explode(\"\\n\", $data);\n foreach ($lines as $line) {\n $frame .= \"data: {$line}\\n\";\n }\n $frame .= \"\\n\";\n\n return $stream->write($frame);\n }\n\n public function close(): void\n {\n if ($this->closing) {\n return;\n }\n\n $this->closing = true;\n $this->listening = false;\n $this->logger->info('Closing transport...');\n\n if ($this->socket) {\n $this->socket->close();\n $this->socket = null;\n }\n\n foreach ($this->activeSseStreams as $streamId => $streamInfo) {\n if ($streamInfo['stream']->isWritable()) {\n $streamInfo['stream']->end();\n }\n }\n\n if ($this->getStream !== null) {\n $this->getStream->end();\n $this->getStream = null;\n }\n\n foreach ($this->pendingRequests as $pendingRequestId => $deferred) {\n $deferred->reject(new TransportException('Transport is closing.'));\n }\n\n $this->activeSseStreams = [];\n $this->pendingRequests = [];\n\n $this->emit('close', ['Transport closed.']);\n $this->removeAllListeners();\n }\n}\n"], ["/server/src/Utils/SchemaValidator.php", "logger = $logger;\n }\n\n /**\n * Validates data against a JSON schema.\n *\n * @param mixed $data The data to validate (should generally be decoded JSON).\n * @param array|object $schema The JSON Schema definition (as PHP array or object).\n * @return list Array of validation errors, empty if valid.\n */\n public function validateAgainstJsonSchema(mixed $data, array|object $schema): array\n {\n if (is_array($data) && empty($data)) {\n $data = new \\stdClass();\n }\n\n try {\n // --- Schema Preparation ---\n if (is_array($schema)) {\n $schemaJson = json_encode($schema, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);\n $schemaObject = json_decode($schemaJson, false, 512, JSON_THROW_ON_ERROR);\n } elseif (is_object($schema)) {\n // This might be overly cautious but safer against varied inputs.\n $schemaJson = json_encode($schema, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);\n $schemaObject = json_decode($schemaJson, false, 512, JSON_THROW_ON_ERROR);\n } else {\n throw new InvalidArgumentException('Schema must be an array or object.');\n }\n\n // --- Data Preparation ---\n // Opis Validator generally prefers objects for object validation\n $dataToValidate = $this->convertDataForValidator($data);\n } catch (JsonException $e) {\n $this->logger->error('MCP SDK: Invalid schema structure provided for validation (JSON conversion failed).', ['exception' => $e]);\n\n return [['pointer' => '', 'keyword' => 'internal', 'message' => 'Invalid schema definition provided (JSON error).']];\n } catch (InvalidArgumentException $e) {\n $this->logger->error('MCP SDK: Invalid schema structure provided for validation.', ['exception' => $e]);\n\n return [['pointer' => '', 'keyword' => 'internal', 'message' => $e->getMessage()]];\n } catch (Throwable $e) {\n $this->logger->error('MCP SDK: Error preparing data/schema for validation.', ['exception' => $e]);\n\n return [['pointer' => '', 'keyword' => 'internal', 'message' => 'Internal validation preparation error.']];\n }\n\n $validator = $this->getJsonSchemaValidator();\n\n try {\n $result = $validator->validate($dataToValidate, $schemaObject);\n } catch (Throwable $e) {\n $this->logger->error('MCP SDK: JSON Schema validation failed internally.', [\n 'exception_message' => $e->getMessage(),\n 'exception_trace' => $e->getTraceAsString(),\n 'data' => json_encode($dataToValidate),\n 'schema' => json_encode($schemaObject),\n ]);\n\n return [['pointer' => '', 'keyword' => 'internal', 'message' => 'Schema validation process failed: ' . $e->getMessage()]];\n }\n\n if ($result->isValid()) {\n return [];\n }\n\n $formattedErrors = [];\n $topError = $result->error();\n\n if ($topError) {\n $this->collectSubErrors($topError, $formattedErrors);\n }\n\n if (empty($formattedErrors) && $topError) { // Fallback\n $formattedErrors[] = [\n 'pointer' => $this->formatJsonPointerPath($topError->data()?->path()),\n 'keyword' => $topError->keyword(),\n 'message' => $this->formatValidationError($topError),\n ];\n }\n\n return $formattedErrors;\n }\n\n /**\n * Get or create the JSON Schema validator instance.\n */\n private function getJsonSchemaValidator(): Validator\n {\n if ($this->jsonSchemaValidator === null) {\n $this->jsonSchemaValidator = new Validator();\n // Potentially configure resolver here if needed later\n }\n\n return $this->jsonSchemaValidator;\n }\n\n /**\n * Recursively converts associative arrays to stdClass objects for validator compatibility.\n */\n private function convertDataForValidator(mixed $data): mixed\n {\n if (is_array($data)) {\n // Check if it's an associative array (keys are not sequential numbers 0..N-1)\n if (! empty($data) && array_keys($data) !== range(0, count($data) - 1)) {\n $obj = new \\stdClass();\n foreach ($data as $key => $value) {\n $obj->{$key} = $this->convertDataForValidator($value);\n }\n\n return $obj;\n } else {\n // It's a list (sequential array), convert items recursively\n return array_map([$this, 'convertDataForValidator'], $data);\n }\n } elseif (is_object($data) && $data instanceof \\stdClass) {\n // Deep copy/convert stdClass objects as well\n $obj = new \\stdClass();\n foreach (get_object_vars($data) as $key => $value) {\n $obj->{$key} = $this->convertDataForValidator($value);\n }\n\n return $obj;\n }\n\n // Leave other objects and scalar types as they are\n return $data;\n }\n\n /**\n * Recursively collects leaf validation errors.\n */\n private function collectSubErrors(ValidationError $error, array &$collectedErrors): void\n {\n $subErrors = $error->subErrors();\n if (empty($subErrors)) {\n $collectedErrors[] = [\n 'pointer' => $this->formatJsonPointerPath($error->data()?->path()),\n 'keyword' => $error->keyword(),\n 'message' => $this->formatValidationError($error),\n ];\n } else {\n foreach ($subErrors as $subError) {\n $this->collectSubErrors($subError, $collectedErrors);\n }\n }\n }\n\n /**\n * Formats the path array into a JSON Pointer string.\n */\n private function formatJsonPointerPath(?array $pathComponents): string\n {\n if ($pathComponents === null || empty($pathComponents)) {\n return '/';\n }\n $escapedComponents = array_map(function ($component) {\n $componentStr = (string) $component;\n\n return str_replace(['~', '/'], ['~0', '~1'], $componentStr);\n }, $pathComponents);\n\n return '/' . implode('/', $escapedComponents);\n }\n\n /**\n * Formats an Opis SchemaValidationError into a user-friendly message.\n */\n private function formatValidationError(ValidationError $error): string\n {\n $keyword = $error->keyword();\n $args = $error->args();\n $message = \"Constraint `{$keyword}` failed.\";\n\n switch (strtolower($keyword)) {\n case 'required':\n $missing = $args['missing'] ?? [];\n $formattedMissing = implode(', ', array_map(fn($p) => \"`{$p}`\", $missing));\n $message = \"Missing required properties: {$formattedMissing}.\";\n break;\n case 'type':\n $expected = implode('|', (array) ($args['expected'] ?? []));\n $used = $args['used'] ?? 'unknown';\n $message = \"Invalid type. Expected `{$expected}`, but received `{$used}`.\";\n break;\n case 'enum':\n $schemaData = $error->schema()?->info()?->data();\n $allowedValues = [];\n if (is_object($schemaData) && property_exists($schemaData, 'enum') && is_array($schemaData->enum)) {\n $allowedValues = $schemaData->enum;\n } elseif (is_array($schemaData) && isset($schemaData['enum']) && is_array($schemaData['enum'])) {\n $allowedValues = $schemaData['enum'];\n } else {\n $this->logger->warning(\"MCP SDK: Could not retrieve 'enum' values from schema info for error.\", ['error_args' => $args]);\n }\n if (empty($allowedValues)) {\n $message = 'Value does not match the allowed enumeration.';\n } else {\n $formattedAllowed = array_map(function ($v) { /* ... formatting logic ... */\n if (is_string($v)) {\n return '\"' . $v . '\"';\n }\n if (is_bool($v)) {\n return $v ? 'true' : 'false';\n }\n if ($v === null) {\n return 'null';\n }\n\n return (string) $v;\n }, $allowedValues);\n $message = 'Value must be one of the allowed values: ' . implode(', ', $formattedAllowed) . '.';\n }\n break;\n case 'const':\n $expected = json_encode($args['expected'] ?? 'null', JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);\n $message = \"Value must be equal to the constant value: {$expected}.\";\n break;\n case 'minLength': // Corrected casing\n $min = $args['min'] ?? '?';\n $message = \"String must be at least {$min} characters long.\";\n break;\n case 'maxLength': // Corrected casing\n $max = $args['max'] ?? '?';\n $message = \"String must not be longer than {$max} characters.\";\n break;\n case 'pattern':\n $pattern = $args['pattern'] ?? '?';\n $message = \"String does not match the required pattern: `{$pattern}`.\";\n break;\n case 'minimum':\n $min = $args['min'] ?? '?';\n $message = \"Number must be greater than or equal to {$min}.\";\n break;\n case 'maximum':\n $max = $args['max'] ?? '?';\n $message = \"Number must be less than or equal to {$max}.\";\n break;\n case 'exclusiveMinimum': // Corrected casing\n $min = $args['min'] ?? '?';\n $message = \"Number must be strictly greater than {$min}.\";\n break;\n case 'exclusiveMaximum': // Corrected casing\n $max = $args['max'] ?? '?';\n $message = \"Number must be strictly less than {$max}.\";\n break;\n case 'multipleOf': // Corrected casing\n $value = $args['value'] ?? '?';\n $message = \"Number must be a multiple of {$value}.\";\n break;\n case 'minItems': // Corrected casing\n $min = $args['min'] ?? '?';\n $message = \"Array must contain at least {$min} items.\";\n break;\n case 'maxItems': // Corrected casing\n $max = $args['max'] ?? '?';\n $message = \"Array must contain no more than {$max} items.\";\n break;\n case 'uniqueItems': // Corrected casing\n $message = 'Array items must be unique.';\n break;\n case 'minProperties': // Corrected casing\n $min = $args['min'] ?? '?';\n $message = \"Object must have at least {$min} properties.\";\n break;\n case 'maxProperties': // Corrected casing\n $max = $args['max'] ?? '?';\n $message = \"Object must have no more than {$max} properties.\";\n break;\n case 'additionalProperties': // Corrected casing\n $unexpected = $args['properties'] ?? [];\n $formattedUnexpected = implode(', ', array_map(fn($p) => \"`{$p}`\", $unexpected));\n $message = \"Object contains unexpected additional properties: {$formattedUnexpected}.\";\n break;\n case 'format':\n $format = $args['format'] ?? 'unknown';\n $message = \"Value does not match the required format: `{$format}`.\";\n break;\n default:\n $builtInMessage = $error->message();\n if ($builtInMessage && $builtInMessage !== 'The data must match the schema') {\n $placeholders = $args ?? [];\n $builtInMessage = preg_replace_callback('/\\{(\\w+)\\}/', function ($match) use ($placeholders) {\n $key = $match[1];\n $value = $placeholders[$key] ?? '{' . $key . '}';\n\n return is_array($value) ? json_encode($value) : (string) $value;\n }, $builtInMessage);\n $message = $builtInMessage;\n }\n break;\n }\n\n return $message;\n }\n}\n"], ["/server/src/Transports/HttpServerTransport.php", " sessionId => SSE Stream */\n private array $activeSseStreams = [];\n\n protected bool $listening = false;\n\n protected bool $closing = false;\n\n protected string $ssePath;\n\n protected string $messagePath;\n\n /**\n * @param string $host Host to bind to (e.g., '127.0.0.1', '0.0.0.0').\n * @param int $port Port to listen on (e.g., 8080).\n * @param string $mcpPathPrefix URL prefix for MCP endpoints (e.g., 'mcp').\n * @param array|null $sslContext Optional SSL context options for React SocketServer (for HTTPS).\n */\n public function __construct(\n private readonly string $host = '127.0.0.1',\n private readonly int $port = 8080,\n private readonly string $mcpPathPrefix = 'mcp',\n private readonly ?array $sslContext = null,\n ) {\n $this->logger = new NullLogger();\n $this->loop = Loop::get();\n $this->ssePath = '/' . trim($mcpPathPrefix, '/') . '/sse';\n $this->messagePath = '/' . trim($mcpPathPrefix, '/') . '/message';\n }\n\n public function setLogger(LoggerInterface $logger): void\n {\n $this->logger = $logger;\n }\n\n public function setLoop(LoopInterface $loop): void\n {\n $this->loop = $loop;\n }\n\n protected function generateId(): string\n {\n return bin2hex(random_bytes(16)); // 32 hex characters\n }\n\n /**\n * Starts the HTTP server listener.\n *\n * @throws TransportException If port binding fails.\n */\n public function listen(): void\n {\n if ($this->listening) {\n throw new TransportException('Http transport is already listening.');\n }\n if ($this->closing) {\n throw new TransportException('Cannot listen, transport is closing/closed.');\n }\n\n $listenAddress = \"{$this->host}:{$this->port}\";\n $protocol = $this->sslContext ? 'https' : 'http';\n\n try {\n $this->socket = new SocketServer(\n $listenAddress,\n $this->sslContext ?? [],\n $this->loop\n );\n\n $this->http = new HttpServer($this->loop, $this->createRequestHandler());\n $this->http->listen($this->socket);\n\n $this->socket->on('error', function (Throwable $error) {\n $this->logger->error('Socket server error.', ['error' => $error->getMessage()]);\n $this->emit('error', [new TransportException(\"Socket server error: {$error->getMessage()}\", 0, $error)]);\n $this->close();\n });\n\n $this->logger->info(\"Server is up and listening on {$protocol}://{$listenAddress} 🚀\");\n $this->logger->info(\"SSE Endpoint: {$protocol}://{$listenAddress}{$this->ssePath}\");\n $this->logger->info(\"Message Endpoint: {$protocol}://{$listenAddress}{$this->messagePath}\");\n\n $this->listening = true;\n $this->closing = false;\n $this->emit('ready');\n } catch (Throwable $e) {\n $this->logger->error(\"Failed to start listener on {$listenAddress}\", ['exception' => $e]);\n throw new TransportException(\"Failed to start HTTP listener on {$listenAddress}: {$e->getMessage()}\", 0, $e);\n }\n }\n\n /** Creates the main request handling callback for ReactPHP HttpServer */\n protected function createRequestHandler(): callable\n {\n return function (ServerRequestInterface $request) {\n $path = $request->getUri()->getPath();\n $method = $request->getMethod();\n $this->logger->debug('Received request', ['method' => $method, 'path' => $path]);\n\n if ($method === 'GET' && $path === $this->ssePath) {\n return $this->handleSseRequest($request);\n }\n\n if ($method === 'POST' && $path === $this->messagePath) {\n return $this->handleMessagePostRequest($request);\n }\n\n $this->logger->debug('404 Not Found', ['method' => $method, 'path' => $path]);\n\n return new Response(404, ['Content-Type' => 'text/plain'], 'Not Found');\n };\n }\n\n /** Handles a new SSE connection request */\n protected function handleSseRequest(ServerRequestInterface $request): Response\n {\n $sessionId = $this->generateId();\n $this->logger->info('New SSE connection', ['sessionId' => $sessionId]);\n\n $sseStream = new ThroughStream();\n\n $sseStream->on('close', function () use ($sessionId) {\n $this->logger->info('SSE stream closed', ['sessionId' => $sessionId]);\n unset($this->activeSseStreams[$sessionId]);\n $this->emit('client_disconnected', [$sessionId, 'SSE stream closed']);\n });\n\n $sseStream->on('error', function (Throwable $error) use ($sessionId) {\n $this->logger->warning('SSE stream error', ['sessionId' => $sessionId, 'error' => $error->getMessage()]);\n unset($this->activeSseStreams[$sessionId]);\n $this->emit('error', [new TransportException(\"SSE Stream Error: {$error->getMessage()}\", 0, $error), $sessionId]);\n $this->emit('client_disconnected', [$sessionId, 'SSE stream error']);\n });\n\n $this->activeSseStreams[$sessionId] = $sseStream;\n\n $this->loop->futureTick(function () use ($sessionId, $request, $sseStream) {\n if (! isset($this->activeSseStreams[$sessionId]) || ! $sseStream->isWritable()) {\n $this->logger->warning('Cannot send initial endpoint event, stream closed/invalid early.', ['sessionId' => $sessionId]);\n\n return;\n }\n\n try {\n $baseUri = $request->getUri()->withPath($this->messagePath)->withQuery('')->withFragment('');\n $postEndpointWithId = (string) $baseUri->withQuery(\"clientId={$sessionId}\");\n $this->sendSseEvent($sseStream, 'endpoint', $postEndpointWithId, \"init-{$sessionId}\");\n\n $this->emit('client_connected', [$sessionId]);\n } catch (Throwable $e) {\n $this->logger->error('Error sending initial endpoint event', ['sessionId' => $sessionId, 'exception' => $e]);\n $sseStream->close();\n }\n });\n\n return new Response(\n 200,\n [\n 'Content-Type' => 'text/event-stream',\n 'Cache-Control' => 'no-cache',\n 'Connection' => 'keep-alive',\n 'X-Accel-Buffering' => 'no',\n 'Access-Control-Allow-Origin' => '*',\n ],\n $sseStream\n );\n }\n\n /** Handles incoming POST requests with messages */\n protected function handleMessagePostRequest(ServerRequestInterface $request): Response\n {\n $queryParams = $request->getQueryParams();\n $sessionId = $queryParams['clientId'] ?? null;\n $jsonEncodeFlags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;\n\n if (! $sessionId || ! is_string($sessionId)) {\n $this->logger->warning('Received POST without valid clientId query parameter.');\n $error = Error::forInvalidRequest('Missing or invalid clientId query parameter');\n\n return new Response(400, ['Content-Type' => 'application/json'], json_encode($error, $jsonEncodeFlags));\n }\n\n if (! isset($this->activeSseStreams[$sessionId])) {\n $this->logger->warning('Received POST for unknown or disconnected sessionId.', ['sessionId' => $sessionId]);\n\n $error = Error::forInvalidRequest('Session ID not found or disconnected');\n\n return new Response(404, ['Content-Type' => 'application/json'], json_encode($error, $jsonEncodeFlags));\n }\n\n if (! str_contains(strtolower($request->getHeaderLine('Content-Type')), 'application/json')) {\n $error = Error::forInvalidRequest('Content-Type must be application/json');\n\n return new Response(415, ['Content-Type' => 'application/json'], json_encode($error, $jsonEncodeFlags));\n }\n\n $body = $request->getBody()->getContents();\n\n if (empty($body)) {\n $this->logger->warning('Received empty POST body', ['sessionId' => $sessionId]);\n\n $error = Error::forInvalidRequest('Empty request body');\n\n return new Response(400, ['Content-Type' => 'application/json'], json_encode($error, $jsonEncodeFlags));\n }\n\n try {\n $message = Parser::parse($body);\n } catch (Throwable $e) {\n $this->logger->error('Error parsing message', ['sessionId' => $sessionId, 'exception' => $e]);\n\n $error = Error::forParseError('Invalid JSON-RPC message: ' . $e->getMessage());\n\n return new Response(400, ['Content-Type' => 'application/json'], json_encode($error, $jsonEncodeFlags));\n }\n\n $this->emit('message', [$message, $sessionId]);\n\n return new Response(202, ['Content-Type' => 'text/plain'], 'Accepted');\n }\n\n\n /**\n * Sends a raw JSON-RPC message frame to a specific client via SSE.\n */\n public function sendMessage(Message $message, string $sessionId, array $context = []): PromiseInterface\n {\n if (! isset($this->activeSseStreams[$sessionId])) {\n return reject(new TransportException(\"Cannot send message: Client '{$sessionId}' not connected via SSE.\"));\n }\n\n $stream = $this->activeSseStreams[$sessionId];\n if (! $stream->isWritable()) {\n return reject(new TransportException(\"Cannot send message: SSE stream for client '{$sessionId}' is not writable.\"));\n }\n\n $json = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);\n\n if ($json === '') {\n return resolve(null);\n }\n\n $deferred = new Deferred();\n $written = $this->sendSseEvent($stream, 'message', $json);\n\n if ($written) {\n $deferred->resolve(null);\n } else {\n $this->logger->debug('SSE stream buffer full, waiting for drain.', ['sessionId' => $sessionId]);\n $stream->once('drain', function () use ($deferred, $sessionId) {\n $this->logger->debug('SSE stream drained.', ['sessionId' => $sessionId]);\n $deferred->resolve(null);\n });\n }\n\n return $deferred->promise();\n }\n\n /** Helper to format and write an SSE event */\n private function sendSseEvent(WritableStreamInterface $stream, string $event, string $data, ?string $id = null): bool\n {\n if (! $stream->isWritable()) {\n return false;\n }\n\n $frame = \"event: {$event}\\n\";\n if ($id !== null) {\n $frame .= \"id: {$id}\\n\";\n }\n\n $lines = explode(\"\\n\", $data);\n foreach ($lines as $line) {\n $frame .= \"data: {$line}\\n\";\n }\n $frame .= \"\\n\"; // End of event\n\n $this->logger->debug('Sending SSE event', ['event' => $event, 'frame' => $frame]);\n\n return $stream->write($frame);\n }\n\n /**\n * Stops the HTTP server and closes all connections.\n */\n public function close(): void\n {\n if ($this->closing) {\n return;\n }\n $this->closing = true;\n $this->listening = false;\n $this->logger->info('Closing transport...');\n\n if ($this->socket) {\n $this->socket->close();\n $this->socket = null;\n }\n\n $activeStreams = $this->activeSseStreams;\n $this->activeSseStreams = [];\n foreach ($activeStreams as $sessionId => $stream) {\n $this->logger->debug('Closing active SSE stream', ['sessionId' => $sessionId]);\n unset($this->activeSseStreams[$sessionId]);\n $stream->close();\n }\n\n $this->emit('close', ['HttpTransport closed.']);\n $this->removeAllListeners();\n }\n}\n"], ["/server/src/Transports/StdioServerTransport.php", "inputStreamResource === STDIN && $this->outputStreamResource === STDOUT)) {\n $message = 'STDIN and STDOUT are not supported as input and output stream resources' .\n 'on Windows due to PHP\\'s limitations with non blocking pipes.' .\n 'Please use WSL or HttpServerTransport, or if you are advanced, provide your own stream resources.';\n\n throw new TransportException($message);\n }\n\n // if (str_contains(PHP_OS, 'WIN')) {\n // $this->inputStreamResource = pclose(popen('winpty -c \"'.$this->inputStreamResource.'\"', 'r'));\n // $this->outputStreamResource = pclose(popen('winpty -c \"'.$this->outputStreamResource.'\"', 'w'));\n // }\n\n if (! is_resource($this->inputStreamResource) || get_resource_type($this->inputStreamResource) !== 'stream') {\n throw new TransportException('Invalid input stream resource provided.');\n }\n\n if (! is_resource($this->outputStreamResource) || get_resource_type($this->outputStreamResource) !== 'stream') {\n throw new TransportException('Invalid output stream resource provided.');\n }\n\n $this->logger = new NullLogger();\n $this->loop = Loop::get();\n }\n\n public function setLogger(LoggerInterface $logger): void\n {\n $this->logger = $logger;\n }\n\n public function setLoop(LoopInterface $loop): void\n {\n $this->loop = $loop;\n }\n\n /**\n * Starts listening on STDIN.\n *\n * @throws TransportException If already listening or streams cannot be opened.\n */\n public function listen(): void\n {\n if ($this->listening) {\n throw new TransportException('Stdio transport is already listening.');\n }\n\n if ($this->closing) {\n throw new TransportException('Cannot listen, transport is closing/closed.');\n }\n\n try {\n $this->stdin = new ReadableResourceStream($this->inputStreamResource, $this->loop);\n $this->stdout = new WritableResourceStream($this->outputStreamResource, $this->loop);\n } catch (Throwable $e) {\n $this->logger->error('Failed to open STDIN/STDOUT streams.', ['exception' => $e]);\n throw new TransportException(\"Failed to open standard streams: {$e->getMessage()}\", 0, $e);\n }\n\n $this->stdin->on('data', function ($chunk) {\n $this->buffer .= $chunk;\n $this->processBuffer();\n });\n\n $this->stdin->on('error', function (Throwable $error) {\n $this->logger->error('STDIN stream error.', ['error' => $error->getMessage()]);\n $this->emit('error', [new TransportException(\"STDIN error: {$error->getMessage()}\", 0, $error), self::CLIENT_ID]);\n $this->close();\n });\n\n $this->stdin->on('close', function () {\n $this->logger->info('STDIN stream closed.');\n $this->emit('client_disconnected', [self::CLIENT_ID, 'STDIN Closed']);\n $this->close();\n });\n\n $this->stdout->on('error', function (Throwable $error) {\n $this->logger->error('STDOUT stream error.', ['error' => $error->getMessage()]);\n $this->emit('error', [new TransportException(\"STDOUT error: {$error->getMessage()}\", 0, $error), self::CLIENT_ID]);\n $this->close();\n });\n\n try {\n $signalHandler = function (int $signal) {\n $this->logger->info(\"Received signal {$signal}, shutting down.\");\n $this->close();\n };\n $this->loop->addSignal(SIGTERM, $signalHandler);\n $this->loop->addSignal(SIGINT, $signalHandler);\n } catch (Throwable $e) {\n $this->logger->debug('Signal handling not supported by current event loop.');\n }\n\n $this->logger->info('Server is up and listening on STDIN 🚀');\n\n $this->listening = true;\n $this->closing = false;\n $this->emit('ready');\n $this->emit('client_connected', [self::CLIENT_ID]);\n }\n\n /** Processes the internal buffer to find complete lines/frames. */\n private function processBuffer(): void\n {\n while (str_contains($this->buffer, \"\\n\")) {\n $pos = strpos($this->buffer, \"\\n\");\n $line = substr($this->buffer, 0, $pos);\n $this->buffer = substr($this->buffer, $pos + 1);\n\n $trimmedLine = trim($line);\n if (empty($trimmedLine)) {\n continue;\n }\n\n try {\n $message = Parser::parse($trimmedLine);\n } catch (Throwable $e) {\n $this->logger->error('Error parsing message', ['exception' => $e]);\n $error = Error::forParseError(\"Invalid JSON: \" . $e->getMessage());\n $this->sendMessage($error, self::CLIENT_ID);\n continue;\n }\n\n $this->emit('message', [$message, self::CLIENT_ID]);\n }\n }\n\n /**\n * Sends a raw, framed message to STDOUT.\n */\n public function sendMessage(Message $message, string $sessionId, array $context = []): PromiseInterface\n {\n if ($this->closing || ! $this->stdout || ! $this->stdout->isWritable()) {\n return reject(new TransportException('Stdio transport is closed or STDOUT is not writable.'));\n }\n\n $deferred = new Deferred();\n $json = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);\n $written = $this->stdout->write($json . \"\\n\");\n\n if ($written) {\n $deferred->resolve(null);\n } else {\n $this->logger->debug('STDOUT buffer full, waiting for drain.');\n $this->stdout->once('drain', function () use ($deferred) {\n $this->logger->debug('STDOUT drained.');\n $deferred->resolve(null);\n });\n }\n\n return $deferred->promise();\n }\n\n /**\n * Stops listening and cleans up resources.\n */\n public function close(): void\n {\n if ($this->closing) {\n return;\n }\n $this->closing = true;\n $this->listening = false;\n $this->logger->info('Closing Stdio transport...');\n\n $this->stdin?->close();\n $this->stdout?->close();\n\n $this->stdin = null;\n $this->stdout = null;\n\n $this->emit('close', ['StdioTransport closed.']);\n $this->removeAllListeners();\n }\n}\n"], ["/server/src/Protocol.php", "logger = $this->configuration->logger;\n $this->subscriptionManager ??= new SubscriptionManager($this->logger);\n $this->dispatcher ??= new Dispatcher($this->configuration, $this->registry, $this->subscriptionManager);\n\n $this->sessionManager->on('session_deleted', function (string $sessionId) {\n $this->subscriptionManager->cleanupSession($sessionId);\n });\n\n $this->registry->on('list_changed', function (string $listType) {\n $this->handleListChanged($listType);\n });\n }\n\n /**\n * Binds this handler to a transport instance by attaching event listeners.\n * Does NOT start the transport's listening process itself.\n */\n public function bindTransport(ServerTransportInterface $transport): void\n {\n if ($this->transport !== null) {\n $this->unbindTransport();\n }\n\n $this->transport = $transport;\n\n $this->listeners = [\n 'message' => [$this, 'processMessage'],\n 'client_connected' => [$this, 'handleClientConnected'],\n 'client_disconnected' => [$this, 'handleClientDisconnected'],\n 'error' => [$this, 'handleTransportError'],\n ];\n\n $this->transport->on('message', $this->listeners['message']);\n $this->transport->on('client_connected', $this->listeners['client_connected']);\n $this->transport->on('client_disconnected', $this->listeners['client_disconnected']);\n $this->transport->on('error', $this->listeners['error']);\n }\n\n /**\n * Detaches listeners from the current transport.\n */\n public function unbindTransport(): void\n {\n if ($this->transport && ! empty($this->listeners)) {\n $this->transport->removeListener('message', $this->listeners['message']);\n $this->transport->removeListener('client_connected', $this->listeners['client_connected']);\n $this->transport->removeListener('client_disconnected', $this->listeners['client_disconnected']);\n $this->transport->removeListener('error', $this->listeners['error']);\n }\n\n $this->transport = null;\n $this->listeners = [];\n }\n\n /**\n * Handles a message received from the transport.\n *\n * Processes via Processor, sends Response/Error.\n */\n public function processMessage(Request|Notification|BatchRequest $message, string $sessionId, array $messageContext = []): void\n {\n $this->logger->debug('Message received.', ['sessionId' => $sessionId, 'message' => $message]);\n\n $session = $this->sessionManager->getSession($sessionId);\n\n if ($session === null) {\n $error = Error::forInvalidRequest('Invalid or expired session. Please re-initialize the session.', $message->id);\n $messageContext['status_code'] = 404;\n\n $this->transport->sendMessage($error, $sessionId, $messageContext)\n ->then(function () use ($sessionId, $error, $messageContext) {\n $this->logger->debug('Response sent.', ['sessionId' => $sessionId, 'payload' => $error, 'context' => $messageContext]);\n })\n ->catch(function (Throwable $e) use ($sessionId) {\n $this->logger->error('Failed to send response.', ['sessionId' => $sessionId, 'error' => $e->getMessage()]);\n });\n\n return;\n }\n\n if ($messageContext['stateless'] ?? false) {\n $session->set('initialized', true);\n $session->set('protocol_version', self::LATEST_PROTOCOL_VERSION);\n $session->set('client_info', ['name' => 'stateless-client', 'version' => '1.0.0']);\n }\n\n $context = new Context(\n $session,\n $messageContext['request'] ?? null,\n );\n\n $response = null;\n\n if ($message instanceof BatchRequest) {\n $response = $this->processBatchRequest($message, $session, $context);\n } elseif ($message instanceof Request) {\n $response = $this->processRequest($message, $session, $context);\n } elseif ($message instanceof Notification) {\n $this->processNotification($message, $session);\n }\n\n $session->save();\n\n if ($response === null) {\n return;\n }\n\n $this->transport->sendMessage($response, $sessionId, $messageContext)\n ->then(function () use ($sessionId, $response) {\n $this->logger->debug('Response sent.', ['sessionId' => $sessionId, 'payload' => $response]);\n })\n ->catch(function (Throwable $e) use ($sessionId) {\n $this->logger->error('Failed to send response.', ['sessionId' => $sessionId, 'error' => $e->getMessage()]);\n });\n }\n\n /**\n * Process a batch message\n */\n private function processBatchRequest(BatchRequest $batch, SessionInterface $session, Context $context): ?BatchResponse\n {\n $items = [];\n\n foreach ($batch->getNotifications() as $notification) {\n $this->processNotification($notification, $session);\n }\n\n foreach ($batch->getRequests() as $request) {\n $items[] = $this->processRequest($request, $session, $context);\n }\n\n return empty($items) ? null : new BatchResponse($items);\n }\n\n /**\n * Process a request message\n */\n private function processRequest(Request $request, SessionInterface $session, Context $context): Response|Error\n {\n try {\n if ($request->method !== 'initialize') {\n $this->assertSessionInitialized($session);\n }\n\n $this->assertRequestCapability($request->method);\n\n $result = $this->dispatcher->handleRequest($request, $context);\n\n return Response::make($request->id, $result);\n } catch (McpServerException $e) {\n $this->logger->debug('MCP Processor caught McpServerException', ['method' => $request->method, 'code' => $e->getCode(), 'message' => $e->getMessage(), 'data' => $e->getData()]);\n\n return $e->toJsonRpcError($request->id);\n } catch (Throwable $e) {\n $this->logger->error('MCP Processor caught unexpected error', [\n 'method' => $request->method,\n 'exception' => $e->getMessage(),\n 'trace' => $e->getTraceAsString(),\n ]);\n\n return new Error(\n jsonrpc: '2.0',\n id: $request->id,\n code: Constants::INTERNAL_ERROR,\n message: 'Internal error processing method ' . $request->method,\n data: $e->getMessage()\n );\n }\n }\n\n /**\n * Process a notification message\n */\n private function processNotification(Notification $notification, SessionInterface $session): void\n {\n $method = $notification->method;\n $params = $notification->params;\n\n try {\n $this->dispatcher->handleNotification($notification, $session);\n } catch (Throwable $e) {\n $this->logger->error('Error while processing notification', ['method' => $method, 'exception' => $e->getMessage()]);\n return;\n }\n }\n\n /**\n * Send a notification to a session\n */\n public function sendNotification(Notification $notification, string $sessionId): PromiseInterface\n {\n if ($this->transport === null) {\n $this->logger->error('Cannot send notification, transport not bound', [\n 'sessionId' => $sessionId,\n 'method' => $notification->method\n ]);\n return reject(new McpServerException('Transport not bound'));\n }\n\n return $this->transport->sendMessage($notification, $sessionId, [])\n ->then(function () {\n return resolve(null);\n })\n ->catch(function (Throwable $e) {\n return reject(new McpServerException('Failed to send notification: ' . $e->getMessage(), previous: $e));\n });\n }\n\n /**\n * Notify subscribers about resource content change\n */\n public function notifyResourceUpdated(string $uri): void\n {\n $subscribers = $this->subscriptionManager->getSubscribers($uri);\n\n if (empty($subscribers)) {\n return;\n }\n\n $notification = ResourceUpdatedNotification::make($uri);\n\n foreach ($subscribers as $sessionId) {\n $this->sendNotification($notification, $sessionId);\n }\n\n $this->logger->debug(\"Sent resource change notification\", [\n 'uri' => $uri,\n 'subscriber_count' => count($subscribers)\n ]);\n }\n\n /**\n * Validate that a session is initialized\n */\n private function assertSessionInitialized(SessionInterface $session): void\n {\n if (!$session->get('initialized', false)) {\n throw McpServerException::invalidRequest('Client session not initialized.');\n }\n }\n\n /**\n * Assert that a request method is enabled\n */\n private function assertRequestCapability(string $method): void\n {\n $capabilities = $this->configuration->capabilities;\n\n switch ($method) {\n case \"ping\":\n case \"initialize\":\n // No specific capability required for these methods\n break;\n\n case 'tools/list':\n case 'tools/call':\n if (!$capabilities->tools) {\n throw McpServerException::methodNotFound($method, 'Tools are not enabled on this server.');\n }\n break;\n\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read':\n if (!$capabilities->resources) {\n throw McpServerException::methodNotFound($method, 'Resources are not enabled on this server.');\n }\n break;\n\n case 'resources/subscribe':\n case 'resources/unsubscribe':\n if (!$capabilities->resources) {\n throw McpServerException::methodNotFound($method, 'Resources are not enabled on this server.');\n }\n if (!$capabilities->resourcesSubscribe) {\n throw McpServerException::methodNotFound($method, 'Resources subscription is not enabled on this server.');\n }\n break;\n\n case 'prompts/list':\n case 'prompts/get':\n if (!$capabilities->prompts) {\n throw McpServerException::methodNotFound($method, 'Prompts are not enabled on this server.');\n }\n break;\n\n case 'logging/setLevel':\n if (!$capabilities->logging) {\n throw McpServerException::methodNotFound($method, 'Logging is not enabled on this server.');\n }\n break;\n\n case 'completion/complete':\n if (!$capabilities->completions) {\n throw McpServerException::methodNotFound($method, 'Completions are not enabled on this server.');\n }\n break;\n\n default:\n break;\n }\n }\n\n private function canSendNotification(string $method): bool\n {\n $capabilities = $this->configuration->capabilities;\n\n $valid = true;\n\n switch ($method) {\n case 'notifications/message':\n if (!$capabilities->logging) {\n $this->logger->warning('Logging is not enabled on this server. Notifications/message will not be sent.');\n $valid = false;\n }\n break;\n\n case \"notifications/resources/updated\":\n case \"notifications/resources/list_changed\":\n if (!$capabilities->resources || !$capabilities->resourcesListChanged) {\n $this->logger->warning('Resources list changed notifications are not enabled on this server. Notifications/resources/list_changed will not be sent.');\n $valid = false;\n }\n break;\n\n case \"notifications/tools/list_changed\":\n if (!$capabilities->tools || !$capabilities->toolsListChanged) {\n $this->logger->warning('Tools list changed notifications are not enabled on this server. Notifications/tools/list_changed will not be sent.');\n $valid = false;\n }\n break;\n\n case \"notifications/prompts/list_changed\":\n if (!$capabilities->prompts || !$capabilities->promptsListChanged) {\n $this->logger->warning('Prompts list changed notifications are not enabled on this server. Notifications/prompts/list_changed will not be sent.');\n $valid = false;\n }\n break;\n\n case \"notifications/cancelled\":\n // Cancellation notifications are always allowed\n break;\n\n case \"notifications/progress\":\n // Progress notifications are always allowed\n break;\n\n default:\n break;\n }\n\n return $valid;\n }\n\n /**\n * Handles 'client_connected' event from the transport\n */\n public function handleClientConnected(string $sessionId): void\n {\n $this->logger->info('Client connected', ['sessionId' => $sessionId]);\n\n $this->sessionManager->createSession($sessionId);\n }\n\n /**\n * Handles 'client_disconnected' event from the transport\n */\n public function handleClientDisconnected(string $sessionId, ?string $reason = null): void\n {\n $this->logger->info('Client disconnected', ['clientId' => $sessionId, 'reason' => $reason ?? 'N/A']);\n\n $this->sessionManager->deleteSession($sessionId);\n }\n\n /**\n * Handle list changed event from registry\n */\n public function handleListChanged(string $listType): void\n {\n $listChangeUri = \"mcp://changes/{$listType}\";\n\n $subscribers = $this->subscriptionManager->getSubscribers($listChangeUri);\n if (empty($subscribers)) {\n return;\n }\n\n $notification = match ($listType) {\n 'resources' => ResourceListChangedNotification::make(),\n 'tools' => ToolListChangedNotification::make(),\n 'prompts' => PromptListChangedNotification::make(),\n 'roots' => RootsListChangedNotification::make(),\n default => throw new \\InvalidArgumentException(\"Invalid list type: {$listType}\"),\n };\n\n if (!$this->canSendNotification($notification->method)) {\n return;\n }\n\n foreach ($subscribers as $sessionId) {\n $this->sendNotification($notification, $sessionId);\n }\n\n $this->logger->debug(\"Sent list change notification\", [\n 'list_type' => $listType,\n 'subscriber_count' => count($subscribers)\n ]);\n }\n\n /**\n * Handles 'error' event from the transport\n */\n public function handleTransportError(Throwable $error, ?string $clientId = null): void\n {\n $context = ['error' => $error->getMessage(), 'exception_class' => get_class($error)];\n\n if ($clientId) {\n $context['clientId'] = $clientId;\n $this->logger->error('Transport error for client', $context);\n } else {\n $this->logger->error('General transport error', $context);\n }\n }\n}\n"], ["/server/src/Defaults/FileCache.php", "ensureDirectoryExists(dirname($this->cacheFile));\n }\n\n // ---------------------------------------------------------------------\n // PSR-16 Methods\n // ---------------------------------------------------------------------\n\n public function get(string $key, mixed $default = null): mixed\n {\n $data = $this->readCacheFile();\n $key = $this->sanitizeKey($key);\n\n if (! isset($data[$key])) {\n return $default;\n }\n\n if ($this->isExpired($data[$key]['expiry'])) {\n $this->delete($key); // Clean up expired entry\n\n return $default;\n }\n\n return $data[$key]['value'] ?? $default;\n }\n\n public function set(string $key, mixed $value, DateInterval|int|null $ttl = null): bool\n {\n $data = $this->readCacheFile();\n $key = $this->sanitizeKey($key);\n\n $data[$key] = [\n 'value' => $value,\n 'expiry' => $this->calculateExpiry($ttl),\n ];\n\n return $this->writeCacheFile($data);\n }\n\n public function delete(string $key): bool\n {\n $data = $this->readCacheFile();\n $key = $this->sanitizeKey($key);\n\n if (isset($data[$key])) {\n unset($data[$key]);\n\n return $this->writeCacheFile($data);\n }\n\n return true; // Key didn't exist, considered successful delete\n }\n\n public function clear(): bool\n {\n // Write an empty array to the file\n return $this->writeCacheFile([]);\n }\n\n public function getMultiple(iterable $keys, mixed $default = null): iterable\n {\n $keys = $this->iterableToArray($keys);\n $this->validateKeys($keys);\n\n $data = $this->readCacheFile();\n $results = [];\n $needsWrite = false;\n\n foreach ($keys as $key) {\n $sanitizedKey = $this->sanitizeKey($key);\n if (! isset($data[$sanitizedKey])) {\n $results[$key] = $default;\n\n continue;\n }\n\n if ($this->isExpired($data[$sanitizedKey]['expiry'])) {\n unset($data[$sanitizedKey]); // Clean up expired entry\n $needsWrite = true;\n $results[$key] = $default;\n\n continue;\n }\n\n $results[$key] = $data[$sanitizedKey]['value'] ?? $default;\n }\n\n if ($needsWrite) {\n $this->writeCacheFile($data);\n }\n\n return $results;\n }\n\n public function setMultiple(iterable $values, DateInterval|int|null $ttl = null): bool\n {\n $values = $this->iterableToArray($values);\n $this->validateKeys(array_keys($values));\n\n $data = $this->readCacheFile();\n $expiry = $this->calculateExpiry($ttl);\n\n foreach ($values as $key => $value) {\n $sanitizedKey = $this->sanitizeKey((string) $key);\n $data[$sanitizedKey] = [\n 'value' => $value,\n 'expiry' => $expiry,\n ];\n }\n\n return $this->writeCacheFile($data);\n }\n\n public function deleteMultiple(iterable $keys): bool\n {\n $keys = $this->iterableToArray($keys);\n $this->validateKeys($keys);\n\n $data = $this->readCacheFile();\n $deleted = false;\n\n foreach ($keys as $key) {\n $sanitizedKey = $this->sanitizeKey($key);\n if (isset($data[$sanitizedKey])) {\n unset($data[$sanitizedKey]);\n $deleted = true;\n }\n }\n\n if ($deleted) {\n return $this->writeCacheFile($data);\n }\n\n return true; // No keys existed or no changes made\n }\n\n public function has(string $key): bool\n {\n $data = $this->readCacheFile();\n $key = $this->sanitizeKey($key);\n\n if (! isset($data[$key])) {\n return false;\n }\n\n if ($this->isExpired($data[$key]['expiry'])) {\n $this->delete($key); // Clean up expired\n\n return false;\n }\n\n return true;\n }\n\n // ---------------------------------------------------------------------\n // Internal Methods\n // ---------------------------------------------------------------------\n\n private function readCacheFile(): array\n {\n if (! file_exists($this->cacheFile) || filesize($this->cacheFile) === 0) {\n return [];\n }\n\n $handle = @fopen($this->cacheFile, 'rb');\n if ($handle === false) {\n return [];\n }\n\n try {\n if (! flock($handle, LOCK_SH)) {\n return [];\n }\n $content = stream_get_contents($handle);\n flock($handle, LOCK_UN);\n\n if ($content === false || $content === '') {\n return [];\n }\n\n $data = unserialize($content);\n if ($data === false) {\n return [];\n }\n\n return $data;\n } finally {\n if (is_resource($handle)) {\n fclose($handle);\n }\n }\n }\n\n private function writeCacheFile(array $data): bool\n {\n $jsonData = serialize($data);\n\n if ($jsonData === false) {\n return false;\n }\n\n $handle = @fopen($this->cacheFile, 'cb');\n if ($handle === false) {\n return false;\n }\n\n try {\n if (! flock($handle, LOCK_EX)) {\n return false;\n }\n if (! ftruncate($handle, 0)) {\n return false;\n }\n if (fwrite($handle, $jsonData) === false) {\n return false;\n }\n fflush($handle);\n flock($handle, LOCK_UN);\n @chmod($this->cacheFile, $this->filePermission);\n\n return true;\n } catch (Throwable $e) {\n flock($handle, LOCK_UN); // Ensure lock release on error\n\n return false;\n } finally {\n if (is_resource($handle)) {\n fclose($handle);\n }\n }\n }\n\n private function ensureDirectoryExists(string $directory): void\n {\n if (! is_dir($directory)) {\n if (! @mkdir($directory, $this->dirPermission, true)) {\n throw new InvalidArgumentException(\"Cache directory does not exist and could not be created: {$directory}\");\n }\n @chmod($directory, $this->dirPermission);\n }\n }\n\n private function calculateExpiry(DateInterval|int|null $ttl): ?int\n {\n if ($ttl === null) {\n return null;\n }\n $now = time();\n if (is_int($ttl)) {\n return $ttl <= 0 ? $now - 1 : $now + $ttl;\n }\n if ($ttl instanceof DateInterval) {\n try {\n return (new DateTimeImmutable())->add($ttl)->getTimestamp();\n } catch (Throwable $e) {\n return null;\n }\n }\n throw new InvalidArgumentException('Invalid TTL type provided. Must be null, int, or DateInterval.');\n }\n\n private function isExpired(?int $expiry): bool\n {\n return $expiry !== null && time() >= $expiry;\n }\n\n private function sanitizeKey(string $key): string\n {\n if ($key === '') {\n throw new InvalidArgumentException('Cache key cannot be empty.');\n }\n\n // PSR-16 validation (optional stricter check)\n // if (preg_match('/[{}()\\/@:]/', $key)) {\n // throw new InvalidArgumentException(\"Cache key \\\"{$key}\\\" contains reserved characters.\");\n // }\n return $key;\n }\n\n private function validateKeys(array $keys): void\n {\n foreach ($keys as $key) {\n if (! is_string($key)) {\n throw new InvalidArgumentException('Cache key must be a string, got ' . gettype($key));\n }\n $this->sanitizeKey($key);\n }\n }\n\n private function iterableToArray(iterable $iterable): array\n {\n if (is_array($iterable)) {\n return $iterable;\n }\n\n return iterator_to_array($iterable);\n }\n}\n"], ["/server/src/Elements/RegisteredElement.php", "handler = $handler;\n $this->isManual = $isManual;\n }\n\n public function handle(ContainerInterface $container, array $arguments, Context $context): mixed\n {\n if (is_string($this->handler)) {\n if (class_exists($this->handler) && method_exists($this->handler, '__invoke')) {\n $reflection = new \\ReflectionMethod($this->handler, '__invoke');\n $arguments = $this->prepareArguments($reflection, $arguments, $context);\n $instance = $container->get($this->handler);\n return call_user_func($instance, ...$arguments);\n }\n\n if (function_exists($this->handler)) {\n $reflection = new \\ReflectionFunction($this->handler);\n $arguments = $this->prepareArguments($reflection, $arguments, $context);\n return call_user_func($this->handler, ...$arguments);\n }\n }\n\n if (is_callable($this->handler)) {\n $reflection = $this->getReflectionForCallable($this->handler);\n $arguments = $this->prepareArguments($reflection, $arguments, $context);\n return call_user_func($this->handler, ...$arguments);\n }\n\n if (is_array($this->handler)) {\n [$className, $methodName] = $this->handler;\n $reflection = new \\ReflectionMethod($className, $methodName);\n $arguments = $this->prepareArguments($reflection, $arguments, $context);\n\n $instance = $container->get($className);\n return call_user_func([$instance, $methodName], ...$arguments);\n }\n\n throw new \\InvalidArgumentException('Invalid handler type');\n }\n\n\n protected function prepareArguments(\\ReflectionFunctionAbstract $reflection, array $arguments, Context $context): array\n {\n $finalArgs = [];\n\n foreach ($reflection->getParameters() as $parameter) {\n // TODO: Handle variadic parameters.\n $paramName = $parameter->getName();\n $paramType = $parameter->getType();\n $paramPosition = $parameter->getPosition();\n\n if ($paramType instanceof ReflectionNamedType && $paramType->getName() === Context::class) {\n $finalArgs[$paramPosition] = $context;\n\n continue;\n }\n\n if (isset($arguments[$paramName])) {\n $argument = $arguments[$paramName];\n try {\n $finalArgs[$paramPosition] = $this->castArgumentType($argument, $parameter);\n } catch (InvalidArgumentException $e) {\n throw McpServerException::invalidParams($e->getMessage(), $e);\n } catch (Throwable $e) {\n throw McpServerException::internalError(\n \"Error processing parameter `{$paramName}`: {$e->getMessage()}\",\n $e\n );\n }\n } elseif ($parameter->isDefaultValueAvailable()) {\n $finalArgs[$paramPosition] = $parameter->getDefaultValue();\n } elseif ($parameter->allowsNull()) {\n $finalArgs[$paramPosition] = null;\n } elseif ($parameter->isOptional()) {\n continue;\n } else {\n $reflectionName = $reflection instanceof \\ReflectionMethod\n ? $reflection->class . '::' . $reflection->name\n : 'Closure';\n throw McpServerException::internalError(\n \"Missing required argument `{$paramName}` for {$reflectionName}.\"\n );\n }\n }\n\n return array_values($finalArgs);\n }\n\n /**\n * Gets a ReflectionMethod or ReflectionFunction for a callable.\n */\n private function getReflectionForCallable(callable $handler): \\ReflectionMethod|\\ReflectionFunction\n {\n if (is_string($handler)) {\n return new \\ReflectionFunction($handler);\n }\n\n if ($handler instanceof \\Closure) {\n return new \\ReflectionFunction($handler);\n }\n\n if (is_array($handler) && count($handler) === 2) {\n [$class, $method] = $handler;\n return new \\ReflectionMethod($class, $method);\n }\n\n throw new \\InvalidArgumentException('Cannot create reflection for this callable type');\n }\n\n /**\n * Attempts type casting based on ReflectionParameter type hints.\n *\n * @throws InvalidArgumentException If casting is impossible for the required type.\n * @throws TypeError If internal PHP casting fails unexpectedly.\n */\n private function castArgumentType(mixed $argument, ReflectionParameter $parameter): mixed\n {\n $type = $parameter->getType();\n\n if ($argument === null) {\n if ($type && $type->allowsNull()) {\n return null;\n }\n }\n\n if (! $type instanceof ReflectionNamedType) {\n return $argument;\n }\n\n $typeName = $type->getName();\n\n if (enum_exists($typeName)) {\n if (is_object($argument) && $argument instanceof $typeName) {\n return $argument;\n }\n\n if (is_subclass_of($typeName, \\BackedEnum::class)) {\n $value = $typeName::tryFrom($argument);\n if ($value === null) {\n throw new InvalidArgumentException(\n \"Invalid value '{$argument}' for backed enum {$typeName}. Expected one of its backing values.\",\n );\n }\n return $value;\n } else {\n if (is_string($argument)) {\n foreach ($typeName::cases() as $case) {\n if ($case->name === $argument) {\n return $case;\n }\n }\n $validNames = array_map(fn($c) => $c->name, $typeName::cases());\n throw new InvalidArgumentException(\n \"Invalid value '{$argument}' for unit enum {$typeName}. Expected one of: \" . implode(', ', $validNames) . \".\"\n );\n } else {\n throw new InvalidArgumentException(\n \"Invalid value type '{$argument}' for unit enum {$typeName}. Expected a string matching a case name.\"\n );\n }\n }\n }\n\n try {\n return match (strtolower($typeName)) {\n 'int', 'integer' => $this->castToInt($argument),\n 'string' => (string) $argument,\n 'bool', 'boolean' => $this->castToBoolean($argument),\n 'float', 'double' => $this->castToFloat($argument),\n 'array' => $this->castToArray($argument),\n default => $argument,\n };\n } catch (TypeError $e) {\n throw new InvalidArgumentException(\n \"Value cannot be cast to required type `{$typeName}`.\",\n 0,\n $e\n );\n }\n }\n\n /** Helper to cast strictly to boolean */\n private function castToBoolean(mixed $argument): bool\n {\n if (is_bool($argument)) {\n return $argument;\n }\n if ($argument === 1 || $argument === '1' || strtolower((string) $argument) === 'true') {\n return true;\n }\n if ($argument === 0 || $argument === '0' || strtolower((string) $argument) === 'false') {\n return false;\n }\n throw new InvalidArgumentException('Cannot cast value to boolean. Use true/false/1/0.');\n }\n\n /** Helper to cast strictly to integer */\n private function castToInt(mixed $argument): int\n {\n if (is_int($argument)) {\n return $argument;\n }\n if (is_numeric($argument) && floor((float) $argument) == $argument && ! is_string($argument)) {\n return (int) $argument;\n }\n if (is_string($argument) && ctype_digit(ltrim($argument, '-'))) {\n return (int) $argument;\n }\n throw new InvalidArgumentException('Cannot cast value to integer. Expected integer representation.');\n }\n\n /** Helper to cast strictly to float */\n private function castToFloat(mixed $argument): float\n {\n if (is_float($argument)) {\n return $argument;\n }\n if (is_int($argument)) {\n return (float) $argument;\n }\n if (is_numeric($argument)) {\n return (float) $argument;\n }\n throw new InvalidArgumentException('Cannot cast value to float. Expected numeric representation.');\n }\n\n /** Helper to cast strictly to array */\n private function castToArray(mixed $argument): array\n {\n if (is_array($argument)) {\n return $argument;\n }\n throw new InvalidArgumentException('Cannot cast value to array. Expected array.');\n }\n\n public function toArray(): array\n {\n return [\n 'handler' => $this->handler,\n 'isManual' => $this->isManual,\n ];\n }\n\n public function jsonSerialize(): array\n {\n return $this->toArray();\n }\n}\n"], ["/server/src/Session/Session.php", " Stores all session data.\n * Keys are snake_case by convention for MCP-specific data.\n *\n * Official keys are:\n * - initialized: bool\n * - client_info: array|null\n * - protocol_version: string|null\n * - subscriptions: array\n * - message_queue: array\n * - log_level: string|null\n */\n protected array $data = [];\n\n public function __construct(\n protected SessionHandlerInterface $handler,\n protected string $id = '',\n ?array $data = null\n ) {\n if (empty($this->id)) {\n $this->id = $this->generateId();\n }\n\n if ($data !== null) {\n $this->hydrate($data);\n } elseif ($sessionData = $this->handler->read($this->id)) {\n $this->data = json_decode($sessionData, true) ?? [];\n }\n }\n\n /**\n * Retrieve an existing session instance from handler or return null if session doesn't exist\n */\n public static function retrieve(string $id, SessionHandlerInterface $handler): ?SessionInterface\n {\n $sessionData = $handler->read($id);\n\n if (!$sessionData) {\n return null;\n }\n\n $data = json_decode($sessionData, true);\n if ($data === null) {\n return null;\n }\n\n return new static($handler, $id, $data);\n }\n\n public function getId(): string\n {\n return $this->id;\n }\n\n public function getHandler(): SessionHandlerInterface\n {\n return $this->handler;\n }\n\n public function generateId(): string\n {\n return bin2hex(random_bytes(16));\n }\n\n public function save(): void\n {\n $this->handler->write($this->id, json_encode($this->data));\n }\n\n public function get(string $key, mixed $default = null): mixed\n {\n $key = explode('.', $key);\n $data = $this->data;\n\n foreach ($key as $segment) {\n if (is_array($data) && array_key_exists($segment, $data)) {\n $data = $data[$segment];\n } else {\n return $default;\n }\n }\n\n return $data;\n }\n\n public function set(string $key, mixed $value, bool $overwrite = true): void\n {\n $segments = explode('.', $key);\n $data = &$this->data;\n\n while (count($segments) > 1) {\n $segment = array_shift($segments);\n if (!isset($data[$segment]) || !is_array($data[$segment])) {\n $data[$segment] = [];\n }\n $data = &$data[$segment];\n }\n\n $lastKey = array_shift($segments);\n if ($overwrite || !isset($data[$lastKey])) {\n $data[$lastKey] = $value;\n }\n }\n\n public function has(string $key): bool\n {\n $key = explode('.', $key);\n $data = $this->data;\n\n foreach ($key as $segment) {\n if (is_array($data) && array_key_exists($segment, $data)) {\n $data = $data[$segment];\n } elseif (is_object($data) && isset($data->{$segment})) {\n $data = $data->{$segment};\n } else {\n return false;\n }\n }\n\n return true;\n }\n\n public function forget(string $key): void\n {\n $segments = explode('.', $key);\n $data = &$this->data;\n\n while (count($segments) > 1) {\n $segment = array_shift($segments);\n if (!isset($data[$segment]) || !is_array($data[$segment])) {\n $data[$segment] = [];\n }\n $data = &$data[$segment];\n }\n\n $lastKey = array_shift($segments);\n if (isset($data[$lastKey])) {\n unset($data[$lastKey]);\n }\n }\n\n public function clear(): void\n {\n $this->data = [];\n }\n\n public function pull(string $key, mixed $default = null): mixed\n {\n $value = $this->get($key, $default);\n $this->forget($key);\n return $value;\n }\n\n public function all(): array\n {\n return $this->data;\n }\n\n public function hydrate(array $attributes): void\n {\n $this->data = array_merge(\n [\n 'initialized' => false,\n 'client_info' => null,\n 'protocol_version' => null,\n 'message_queue' => [],\n 'log_level' => null,\n ],\n $attributes\n );\n unset($this->data['id']);\n }\n\n public function queueMessage(string $rawFramedMessage): void\n {\n $this->data['message_queue'][] = $rawFramedMessage;\n }\n\n public function dequeueMessages(): array\n {\n $messages = $this->data['message_queue'] ?? [];\n $this->data['message_queue'] = [];\n return $messages;\n }\n\n public function hasQueuedMessages(): bool\n {\n return !empty($this->data['message_queue']);\n }\n\n public function jsonSerialize(): array\n {\n return $this->all();\n }\n}\n"], ["/server/src/Utils/HandlerResolver.php", "isPublic()) {\n throw new InvalidArgumentException(\"Handler method '{$className}::{$methodName}' must be public.\");\n }\n if ($reflectionMethod->isAbstract()) {\n throw new InvalidArgumentException(\"Handler method '{$className}::{$methodName}' cannot be abstract.\");\n }\n if ($reflectionMethod->isConstructor() || $reflectionMethod->isDestructor()) {\n throw new InvalidArgumentException(\"Handler method '{$className}::{$methodName}' cannot be a constructor or destructor.\");\n }\n\n return $reflectionMethod;\n } catch (ReflectionException $e) {\n // This typically occurs if class_exists passed but ReflectionMethod still fails (rare)\n throw new InvalidArgumentException(\"Reflection error for handler '{$className}::{$methodName}': {$e->getMessage()}\", 0, $e);\n }\n }\n}\n"], ["/server/src/Server.php", "...->build().\n *\n * @param Configuration $configuration Core configuration and dependencies.\n * @param Registry $registry Holds registered MCP element definitions.\n * @param Protocol $protocol Handles MCP requests and responses.\n */\n public function __construct(\n protected readonly Configuration $configuration,\n protected readonly Registry $registry,\n protected readonly Protocol $protocol,\n protected readonly SessionManager $sessionManager,\n ) {\n }\n\n public static function make(): ServerBuilder\n {\n return new ServerBuilder();\n }\n\n /**\n * Runs the attribute discovery process based on the configuration\n * provided during build time. Caches results if cache is available.\n * Can be called explicitly, but is also called by ServerBuilder::build()\n * if discovery paths are configured.\n *\n * @param bool $force Re-run discovery even if already run.\n * @param bool $useCache Attempt to load from/save to cache. Defaults to true if cache is available.\n *\n * @throws DiscoveryException If discovery process encounters errors.\n * @throws ConfigurationException If discovery paths were not configured.\n */\n public function discover(\n string $basePath,\n array $scanDirs = ['.', 'src'],\n array $excludeDirs = [],\n bool $force = false,\n bool $saveToCache = true,\n ?Discoverer $discoverer = null\n ): void {\n $realBasePath = realpath($basePath);\n if ($realBasePath === false || ! is_dir($realBasePath)) {\n throw new \\InvalidArgumentException(\"Invalid discovery base path provided to discover(): {$basePath}\");\n }\n\n $excludeDirs = array_merge($excludeDirs, ['vendor', 'tests', 'test', 'storage', 'cache', 'samples', 'docs', 'node_modules', '.git', '.svn']);\n\n if ($this->discoveryRan && ! $force) {\n $this->configuration->logger->debug('Discovery skipped: Already run or loaded from cache.');\n\n return;\n }\n\n $cacheAvailable = $this->configuration->cache !== null;\n $shouldSaveCache = $saveToCache && $cacheAvailable;\n\n $this->configuration->logger->info('Starting MCP element discovery...', [\n 'basePath' => $realBasePath,\n 'force' => $force,\n 'saveToCache' => $shouldSaveCache,\n ]);\n\n $this->registry->clear();\n\n try {\n $discoverer ??= new Discoverer($this->registry, $this->configuration->logger);\n\n $discoverer->discover($realBasePath, $scanDirs, $excludeDirs);\n\n $this->discoveryRan = true;\n\n if ($shouldSaveCache) {\n $this->registry->save();\n }\n } catch (Throwable $e) {\n $this->discoveryRan = false;\n $this->configuration->logger->critical('MCP element discovery failed.', ['exception' => $e]);\n throw new DiscoveryException(\"Element discovery failed: {$e->getMessage()}\", $e->getCode(), $e);\n }\n }\n\n /**\n * Binds the server's MCP logic to the provided transport and starts the transport's listener,\n * then runs the event loop, making this a BLOCKING call suitable for standalone servers.\n *\n * For framework integration where the loop is managed externally, use `getProtocol()`\n * and bind it to your framework's transport mechanism manually.\n *\n * @param ServerTransportInterface $transport The transport to listen with.\n *\n * @throws LogicException If called after already listening.\n * @throws Throwable If transport->listen() fails immediately.\n */\n public function listen(ServerTransportInterface $transport, bool $runLoop = true): void\n {\n if ($this->isListening) {\n throw new LogicException('Server is already listening via a transport.');\n }\n\n $this->warnIfNoElements();\n\n if ($transport instanceof LoggerAwareInterface) {\n $transport->setLogger($this->configuration->logger);\n }\n if ($transport instanceof LoopAwareInterface) {\n $transport->setLoop($this->configuration->loop);\n }\n\n $protocol = $this->getProtocol();\n\n $closeHandlerCallback = function (?string $reason = null) use ($protocol) {\n $this->isListening = false;\n $this->configuration->logger->info('Transport closed.', ['reason' => $reason ?? 'N/A']);\n $protocol->unbindTransport();\n $this->configuration->loop->stop();\n };\n\n $transport->once('close', $closeHandlerCallback);\n\n $protocol->bindTransport($transport);\n\n try {\n $transport->listen();\n\n $this->isListening = true;\n\n if ($runLoop) {\n $this->sessionManager->startGcTimer();\n\n $this->configuration->loop->run();\n\n $this->endListen($transport);\n }\n } catch (Throwable $e) {\n $this->configuration->logger->critical('Failed to start listening or event loop crashed.', ['exception' => $e->getMessage()]);\n $this->endListen($transport);\n throw $e;\n }\n }\n\n public function endListen(ServerTransportInterface $transport): void\n {\n $protocol = $this->getProtocol();\n\n $protocol->unbindTransport();\n\n $this->sessionManager->stopGcTimer();\n\n $transport->removeAllListeners('close');\n $transport->close();\n\n $this->isListening = false;\n $this->configuration->logger->info(\"Server '{$this->configuration->serverInfo->name}' listener shut down.\");\n }\n\n /**\n * Warns if no MCP elements are registered and discovery has not been run.\n */\n protected function warnIfNoElements(): void\n {\n if (! $this->registry->hasElements() && ! $this->discoveryRan) {\n $this->configuration->logger->warning(\n 'Starting listener, but no MCP elements are registered and discovery has not been run. ' .\n 'Call $server->discover(...) at least once to find and cache elements before listen().'\n );\n } elseif (! $this->registry->hasElements() && $this->discoveryRan) {\n $this->configuration->logger->warning(\n 'Starting listener, but no MCP elements were found after discovery/cache load.'\n );\n }\n }\n\n /**\n * Gets the Configuration instance associated with this server.\n */\n public function getConfiguration(): Configuration\n {\n return $this->configuration;\n }\n\n /**\n * Gets the Registry instance associated with this server.\n */\n public function getRegistry(): Registry\n {\n return $this->registry;\n }\n\n /**\n * Gets the Protocol instance associated with this server.\n */\n public function getProtocol(): Protocol\n {\n return $this->protocol;\n }\n\n public function getSessionManager(): SessionManager\n {\n return $this->sessionManager;\n }\n}\n"], ["/server/src/Defaults/BasicContainer.php", " Cache for already created instances (shared singletons) */\n private array $instances = [];\n\n /** @var array Track classes currently being resolved to detect circular dependencies */\n private array $resolving = [];\n\n /**\n * Finds an entry of the container by its identifier and returns it.\n *\n * @param string $id Identifier of the entry to look for (usually a FQCN).\n * @return mixed Entry.\n *\n * @throws NotFoundExceptionInterface No entry was found for **this** identifier.\n * @throws ContainerExceptionInterface Error while retrieving the entry (e.g., dependency resolution failure, circular dependency).\n */\n public function get(string $id): mixed\n {\n // 1. Check instance cache\n if (isset($this->instances[$id])) {\n return $this->instances[$id];\n }\n\n // 2. Check if class exists\n if (! class_exists($id) && ! interface_exists($id)) { // Also check interface for bindings\n throw new NotFoundException(\"Class, interface, or entry '{$id}' not found.\");\n }\n\n // 7. Circular Dependency Check\n if (isset($this->resolving[$id])) {\n throw new ContainerException(\"Circular dependency detected while resolving '{$id}'. Resolution path: \".implode(' -> ', array_keys($this->resolving)).\" -> {$id}\");\n }\n\n $this->resolving[$id] = true; // Mark as currently resolving\n\n try {\n // 3. Reflect on the class\n $reflector = new ReflectionClass($id);\n\n // Check if class is instantiable (abstract classes, interfaces cannot be directly instantiated)\n if (! $reflector->isInstantiable()) {\n // We might have an interface bound to a concrete class via set()\n // This check is slightly redundant due to class_exists but good practice\n throw new ContainerException(\"Class '{$id}' is not instantiable (e.g., abstract class or interface without explicit binding).\");\n }\n\n // 4. Get the constructor\n $constructor = $reflector->getConstructor();\n\n // 5. If no constructor or constructor has no parameters, instantiate directly\n if ($constructor === null || $constructor->getNumberOfParameters() === 0) {\n $instance = $reflector->newInstance();\n } else {\n // 6. Constructor has parameters, attempt to resolve them\n $parameters = $constructor->getParameters();\n $resolvedArgs = [];\n\n foreach ($parameters as $parameter) {\n $resolvedArgs[] = $this->resolveParameter($parameter, $id);\n }\n\n // Instantiate with resolved arguments\n $instance = $reflector->newInstanceArgs($resolvedArgs);\n }\n\n // Cache the instance\n $this->instances[$id] = $instance;\n\n return $instance;\n\n } catch (ReflectionException $e) {\n throw new ContainerException(\"Reflection failed for '{$id}'.\", 0, $e);\n } catch (ContainerExceptionInterface $e) { // Re-throw container exceptions directly\n throw $e;\n } catch (Throwable $e) { // Catch other instantiation errors\n throw new ContainerException(\"Failed to instantiate or resolve dependencies for '{$id}': \".$e->getMessage(), (int) $e->getCode(), $e);\n } finally {\n // 7. Remove from resolving stack once done (success or failure)\n unset($this->resolving[$id]);\n }\n }\n\n /**\n * Attempts to resolve a single constructor parameter.\n *\n * @throws ContainerExceptionInterface If a required dependency cannot be resolved.\n */\n private function resolveParameter(ReflectionParameter $parameter, string $consumerClassId): mixed\n {\n // Check for type hint\n $type = $parameter->getType();\n\n if ($type instanceof ReflectionNamedType && ! $type->isBuiltin()) {\n // Type hint is a class or interface name\n $typeName = $type->getName();\n try {\n // Recursively get the dependency\n return $this->get($typeName);\n } catch (NotFoundExceptionInterface $e) {\n // Dependency class not found, fail ONLY if required\n if (! $parameter->isOptional() && ! $parameter->allowsNull()) {\n throw new ContainerException(\"Unresolvable dependency '{$typeName}' required by '{$consumerClassId}' constructor parameter \\${$parameter->getName()}.\", 0, $e);\n }\n // If optional or nullable, proceed (will check allowsNull/Default below)\n } catch (ContainerExceptionInterface $e) {\n // Dependency itself failed to resolve (e.g., its own deps, circular)\n throw new ContainerException(\"Failed to resolve dependency '{$typeName}' for '{$consumerClassId}' parameter \\${$parameter->getName()}: \".$e->getMessage(), 0, $e);\n }\n }\n\n // Check if parameter has a default value\n if ($parameter->isDefaultValueAvailable()) {\n return $parameter->getDefaultValue();\n }\n\n // Check if parameter allows null (and wasn't resolved above)\n if ($parameter->allowsNull()) {\n return null;\n }\n\n // Check if it was a built-in type without a default (unresolvable by this basic container)\n if ($type instanceof ReflectionNamedType && $type->isBuiltin()) {\n throw new ContainerException(\"Cannot auto-wire built-in type '{$type->getName()}' for required parameter \\${$parameter->getName()} in '{$consumerClassId}' constructor. Provide a default value or use a more advanced container.\");\n }\n\n // Check if it was a union/intersection type without a default (also unresolvable)\n if ($type !== null && ! $type instanceof ReflectionNamedType) {\n throw new ContainerException(\"Cannot auto-wire complex type (union/intersection) for required parameter \\${$parameter->getName()} in '{$consumerClassId}' constructor. Provide a default value or use a more advanced container.\");\n }\n\n // If we reach here, it's an untyped, required parameter without a default.\n // Or potentially an unresolvable optional class dependency where null is not allowed (edge case).\n throw new ContainerException(\"Cannot resolve required parameter \\${$parameter->getName()} for '{$consumerClassId}' constructor (untyped or unresolvable complex type).\");\n }\n\n /**\n * Returns true if the container can return an entry for the given identifier.\n * Checks explicitly set instances and if the class/interface exists.\n * Does not guarantee `get()` will succeed if auto-wiring fails.\n */\n public function has(string $id): bool\n {\n return isset($this->instances[$id]) || class_exists($id) || interface_exists($id);\n }\n\n /**\n * Adds a pre-built instance or a factory/binding to the container.\n * This basic version only supports pre-built instances (singletons).\n */\n public function set(string $id, object $instance): void\n {\n // Could add support for closures/factories later if needed\n $this->instances[$id] = $instance;\n }\n}\n\n// Keep custom exception classes as they are PSR-11 compliant placeholders\nclass ContainerException extends \\Exception implements ContainerExceptionInterface\n{\n}\nclass NotFoundException extends \\Exception implements NotFoundExceptionInterface\n{\n}\n"], ["/server/src/Exception/McpServerException.php", "data = $data;\n }\n\n /**\n * Get additional error data.\n *\n * @return mixed|null\n */\n public function getData(): mixed\n {\n return $this->data;\n }\n\n /**\n * Formats the exception into a JSON-RPC 2.0 error object structure.\n * Specific exceptions should override this or provide factories with correct codes.\n */\n public function toJsonRpcError(string|int $id): JsonRpcError\n {\n $code = ($this->code >= -32768 && $this->code <= -32000) ? $this->code : Constants::INTERNAL_ERROR;\n\n return new JsonRpcError(\n jsonrpc: '2.0',\n id: $id,\n code: $code,\n message: $this->getMessage(),\n data: $this->getData()\n );\n }\n\n public static function parseError(string $details, ?Throwable $previous = null): self\n {\n return new ProtocolException('Parse error: ' . $details, Constants::PARSE_ERROR, null, $previous);\n }\n\n public static function invalidRequest(?string $details = 'Invalid Request', ?Throwable $previous = null): self\n {\n return new ProtocolException($details, Constants::INVALID_REQUEST, null, $previous);\n }\n\n public static function methodNotFound(string $methodName, ?string $message = null, ?Throwable $previous = null): self\n {\n return new ProtocolException($message ?? \"Method not found: {$methodName}\", Constants::METHOD_NOT_FOUND, null, $previous);\n }\n\n public static function invalidParams(string $message = 'Invalid params', $data = null, ?Throwable $previous = null): self\n {\n // Pass data (e.g., validation errors) through\n return new ProtocolException($message, Constants::INVALID_PARAMS, $data, $previous);\n }\n\n public static function internalError(?string $details = 'Internal server error', ?Throwable $previous = null): self\n {\n $message = 'Internal error';\n if ($details && is_string($details)) {\n $message .= ': ' . $details;\n } elseif ($previous && $details === null) {\n $message .= ' (See server logs)';\n }\n\n return new McpServerException($message, Constants::INTERNAL_ERROR, null, $previous);\n }\n\n public static function toolExecutionFailed(string $toolName, ?Throwable $previous = null): self\n {\n $message = \"Execution failed for tool '{$toolName}'\";\n if ($previous) {\n $message .= ': ' . $previous->getMessage();\n }\n\n return new McpServerException($message, Constants::INTERNAL_ERROR, null, $previous);\n }\n\n public static function resourceReadFailed(string $uri, ?Throwable $previous = null): self\n {\n $message = \"Failed to read resource '{$uri}'\";\n if ($previous) {\n $message .= ': ' . $previous->getMessage();\n }\n\n return new McpServerException($message, Constants::INTERNAL_ERROR, null, $previous);\n }\n\n public static function promptGenerationFailed(string $promptName, ?Throwable $previous = null): self\n {\n $message = \"Failed to generate prompt '{$promptName}'\";\n if ($previous) {\n $message .= ': ' . $previous->getMessage();\n }\n\n return new McpServerException($message, Constants::INTERNAL_ERROR, null, $previous);\n }\n}\n"], ["/server/src/Utils/DocBlockParser.php", "docBlockFactory = DocBlockFactory::createInstance();\n $this->logger = $logger ?? new NullLogger();\n }\n\n /**\n * Safely parses a DocComment string into a DocBlock object.\n */\n public function parseDocBlock(string|null|false $docComment): ?DocBlock\n {\n if ($docComment === false || $docComment === null || empty($docComment)) {\n return null;\n }\n try {\n return $this->docBlockFactory->create($docComment);\n } catch (Throwable $e) {\n // Log error or handle gracefully if invalid DocBlock syntax is encountered\n $this->logger->warning('Failed to parse DocBlock', [\n 'error' => $e->getMessage(),\n 'exception_trace' => $e->getTraceAsString(),\n ]);\n\n return null;\n }\n }\n\n /**\n * Gets the summary line from a DocBlock.\n */\n public function getSummary(?DocBlock $docBlock): ?string\n {\n if (! $docBlock) {\n return null;\n }\n $summary = trim($docBlock->getSummary());\n\n return $summary ?: null; // Return null if empty after trimming\n }\n\n /**\n * Gets the description from a DocBlock (summary + description body).\n */\n public function getDescription(?DocBlock $docBlock): ?string\n {\n if (! $docBlock) {\n return null;\n }\n $summary = trim($docBlock->getSummary());\n $descriptionBody = trim((string) $docBlock->getDescription());\n\n if ($summary && $descriptionBody) {\n return $summary . \"\\n\\n\" . $descriptionBody;\n }\n if ($summary) {\n return $summary;\n }\n if ($descriptionBody) {\n return $descriptionBody;\n }\n\n return null;\n }\n\n /**\n * Extracts @param tag information from a DocBlock, keyed by variable name (e.g., '$paramName').\n *\n * @return array\n */\n public function getParamTags(?DocBlock $docBlock): array\n {\n if (! $docBlock) {\n return [];\n }\n\n /** @var array $paramTags */\n $paramTags = [];\n foreach ($docBlock->getTagsByName('param') as $tag) {\n if ($tag instanceof Param && $tag->getVariableName()) {\n $paramTags['$' . $tag->getVariableName()] = $tag;\n }\n }\n\n return $paramTags;\n }\n\n /**\n * Gets the @return tag information from a DocBlock.\n */\n public function getReturnTag(?DocBlock $docBlock): ?Return_\n {\n if (! $docBlock) {\n return null;\n }\n /** @var Return_|null $returnTag */\n $returnTag = $docBlock->getTagsByName('return')[0] ?? null;\n\n return $returnTag;\n }\n\n /**\n * Gets the description string from a Param tag.\n */\n public function getParamDescription(?Param $paramTag): ?string\n {\n return $paramTag ? (trim((string) $paramTag->getDescription()) ?: null) : null;\n }\n\n /**\n * Gets the type string from a Param tag.\n */\n public function getParamTypeString(?Param $paramTag): ?string\n {\n if ($paramTag && $paramTag->getType()) {\n $typeFromTag = trim((string) $paramTag->getType());\n if (! empty($typeFromTag)) {\n return ltrim($typeFromTag, '\\\\');\n }\n }\n\n return null;\n }\n\n /**\n * Gets the description string from a Return_ tag.\n */\n public function getReturnDescription(?Return_ $returnTag): ?string\n {\n return $returnTag ? (trim((string) $returnTag->getDescription()) ?: null) : null;\n }\n\n /**\n * Gets the type string from a Return_ tag.\n */\n public function getReturnTypeString(?Return_ $returnTag): ?string\n {\n if ($returnTag && $returnTag->getType()) {\n $typeFromTag = trim((string) $returnTag->getType());\n if (! empty($typeFromTag)) {\n return ltrim($typeFromTag, '\\\\');\n }\n }\n\n return null;\n }\n}\n"], ["/server/src/Attributes/McpResource.php", "> Key: URI, Value: array of session IDs */\n private array $resourceSubscribers = [];\n\n /** @var array> Key: Session ID, Value: array of URIs */\n private array $sessionSubscriptions = [];\n\n public function __construct(\n private readonly LoggerInterface $logger\n ) {\n }\n\n /**\n * Subscribe a session to a resource\n */\n public function subscribe(string $sessionId, string $uri): void\n {\n // Add to both mappings for efficient lookup\n $this->resourceSubscribers[$uri][$sessionId] = true;\n $this->sessionSubscriptions[$sessionId][$uri] = true;\n\n $this->logger->debug('Session subscribed to resource', [\n 'sessionId' => $sessionId,\n 'uri' => $uri\n ]);\n }\n\n /**\n * Unsubscribe a session from a resource\n */\n public function unsubscribe(string $sessionId, string $uri): void\n {\n unset($this->resourceSubscribers[$uri][$sessionId]);\n unset($this->sessionSubscriptions[$sessionId][$uri]);\n\n // Clean up empty arrays\n if (empty($this->resourceSubscribers[$uri])) {\n unset($this->resourceSubscribers[$uri]);\n }\n\n $this->logger->debug('Session unsubscribed from resource', [\n 'sessionId' => $sessionId,\n 'uri' => $uri\n ]);\n }\n\n /**\n * Get all sessions subscribed to a resource\n */\n public function getSubscribers(string $uri): array\n {\n return array_keys($this->resourceSubscribers[$uri] ?? []);\n }\n\n /**\n * Check if a session is subscribed to a resource\n */\n public function isSubscribed(string $sessionId, string $uri): bool\n {\n return isset($this->sessionSubscriptions[$sessionId][$uri]);\n }\n\n /**\n * Clean up all subscriptions for a session\n */\n public function cleanupSession(string $sessionId): void\n {\n if (!isset($this->sessionSubscriptions[$sessionId])) {\n return;\n }\n\n $uris = array_keys($this->sessionSubscriptions[$sessionId]);\n foreach ($uris as $uri) {\n unset($this->resourceSubscribers[$uri][$sessionId]);\n\n // Clean up empty arrays\n if (empty($this->resourceSubscribers[$uri])) {\n unset($this->resourceSubscribers[$uri]);\n }\n }\n\n unset($this->sessionSubscriptions[$sessionId]);\n\n $this->logger->debug('Cleaned up all subscriptions for session', [\n 'sessionId' => $sessionId,\n 'count' => count($uris)\n ]);\n }\n}\n"], ["/server/src/Session/SessionManager.php", "loop ??= Loop::get();\n }\n\n /**\n * Start the garbage collection timer\n */\n public function startGcTimer(): void\n {\n if ($this->gcTimer !== null) {\n return;\n }\n\n $this->gcTimer = $this->loop->addPeriodicTimer($this->gcInterval, [$this, 'gc']);\n }\n\n public function gc(): array\n {\n $deletedSessions = $this->handler->gc($this->ttl);\n\n foreach ($deletedSessions as $sessionId) {\n $this->emit('session_deleted', [$sessionId]);\n }\n\n if (count($deletedSessions) > 0) {\n $this->logger->debug('Session garbage collection complete', [\n 'purged_sessions' => count($deletedSessions),\n ]);\n }\n\n return $deletedSessions;\n }\n\n /**\n * Stop the garbage collection timer\n */\n public function stopGcTimer(): void\n {\n if ($this->gcTimer !== null) {\n $this->loop->cancelTimer($this->gcTimer);\n $this->gcTimer = null;\n }\n }\n\n /**\n * Create a new session\n */\n public function createSession(string $sessionId): SessionInterface\n {\n $session = new Session($this->handler, $sessionId);\n\n $session->hydrate([\n 'initialized' => false,\n 'client_info' => null,\n 'protocol_version' => null,\n 'subscriptions' => [], // [uri => true]\n 'message_queue' => [], // string[] (raw JSON-RPC frames)\n 'log_level' => null,\n ]);\n\n $session->save();\n\n $this->logger->info('Session created', ['sessionId' => $sessionId]);\n $this->emit('session_created', [$sessionId, $session]);\n\n return $session;\n }\n\n /**\n * Get an existing session\n */\n public function getSession(string $sessionId): ?SessionInterface\n {\n return Session::retrieve($sessionId, $this->handler);\n }\n\n public function hasSession(string $sessionId): bool\n {\n return $this->getSession($sessionId) !== null;\n }\n\n /**\n * Delete a session completely\n */\n public function deleteSession(string $sessionId): bool\n {\n $success = $this->handler->destroy($sessionId);\n\n if ($success) {\n $this->emit('session_deleted', [$sessionId]);\n $this->logger->info('Session deleted', ['sessionId' => $sessionId]);\n } else {\n $this->logger->warning('Failed to delete session', ['sessionId' => $sessionId]);\n }\n\n return $success;\n }\n\n public function queueMessage(string $sessionId, string $message): void\n {\n $session = $this->getSession($sessionId);\n if ($session === null) {\n return;\n }\n\n $session->queueMessage($message);\n $session->save();\n }\n\n public function dequeueMessages(string $sessionId): array\n {\n $session = $this->getSession($sessionId);\n if ($session === null) {\n return [];\n }\n\n $messages = $session->dequeueMessages();\n $session->save();\n\n return $messages;\n }\n\n public function hasQueuedMessages(string $sessionId): bool\n {\n $session = $this->getSession($sessionId, true);\n if ($session === null) {\n return false;\n }\n\n return $session->hasQueuedMessages();\n }\n}\n"], ["/server/src/Attributes/Schema.php", " [schema array], ...]\n public ?array $required = null; // [propertyName, ...]\n public bool|array|null $additionalProperties = null; // true, false, or a schema array\n\n /**\n * @param array|null $definition A complete JSON schema array. If provided, other parameters are ignored.\n * @param Type|null $type The JSON schema type.\n * @param string|null $description Description of the element.\n * @param array|null $enum Allowed enum values.\n * @param string|null $format String format (e.g., 'date-time', 'email').\n * @param int|null $minLength Minimum length for strings.\n * @param int|null $maxLength Maximum length for strings.\n * @param string|null $pattern Regex pattern for strings.\n * @param int|float|null $minimum Minimum value for numbers/integers.\n * @param int|float|null $maximum Maximum value for numbers/integers.\n * @param bool|null $exclusiveMinimum Exclusive minimum.\n * @param bool|null $exclusiveMaximum Exclusive maximum.\n * @param int|float|null $multipleOf Must be a multiple of this value.\n * @param array|null $items JSON Schema for items if type is 'array'.\n * @param int|null $minItems Minimum items for an array.\n * @param int|null $maxItems Maximum items for an array.\n * @param bool|null $uniqueItems Whether array items must be unique.\n * @param array|null $properties Property definitions if type is 'object'. [name => schema_array].\n * @param array|null $required List of required properties for an object.\n * @param bool|array|null $additionalProperties Policy for additional properties in an object.\n */\n public function __construct(\n ?array $definition = null,\n ?string $type = null,\n ?string $description = null,\n ?array $enum = null,\n ?string $format = null,\n ?int $minLength = null,\n ?int $maxLength = null,\n ?string $pattern = null,\n int|float|null $minimum = null,\n int|float|null $maximum = null,\n ?bool $exclusiveMinimum = null,\n ?bool $exclusiveMaximum = null,\n int|float|null $multipleOf = null,\n ?array $items = null,\n ?int $minItems = null,\n ?int $maxItems = null,\n ?bool $uniqueItems = null,\n ?array $properties = null,\n ?array $required = null,\n bool|array|null $additionalProperties = null\n ) {\n if ($definition !== null) {\n $this->definition = $definition;\n } else {\n $this->type = $type;\n $this->description = $description;\n $this->enum = $enum;\n $this->format = $format;\n $this->minLength = $minLength;\n $this->maxLength = $maxLength;\n $this->pattern = $pattern;\n $this->minimum = $minimum;\n $this->maximum = $maximum;\n $this->exclusiveMinimum = $exclusiveMinimum;\n $this->exclusiveMaximum = $exclusiveMaximum;\n $this->multipleOf = $multipleOf;\n $this->items = $items;\n $this->minItems = $minItems;\n $this->maxItems = $maxItems;\n $this->uniqueItems = $uniqueItems;\n $this->properties = $properties;\n $this->required = $required;\n $this->additionalProperties = $additionalProperties;\n }\n }\n\n /**\n * Converts the attribute's definition to a JSON schema array.\n */\n public function toArray(): array\n {\n if ($this->definition !== null) {\n return [\n 'definition' => $this->definition,\n ];\n }\n\n $schema = [];\n if ($this->type !== null) {\n $schema['type'] = $this->type;\n }\n if ($this->description !== null) {\n $schema['description'] = $this->description;\n }\n if ($this->enum !== null) {\n $schema['enum'] = $this->enum;\n }\n if ($this->format !== null) {\n $schema['format'] = $this->format;\n }\n\n // String\n if ($this->minLength !== null) {\n $schema['minLength'] = $this->minLength;\n }\n if ($this->maxLength !== null) {\n $schema['maxLength'] = $this->maxLength;\n }\n if ($this->pattern !== null) {\n $schema['pattern'] = $this->pattern;\n }\n\n // Numeric\n if ($this->minimum !== null) {\n $schema['minimum'] = $this->minimum;\n }\n if ($this->maximum !== null) {\n $schema['maximum'] = $this->maximum;\n }\n if ($this->exclusiveMinimum !== null) {\n $schema['exclusiveMinimum'] = $this->exclusiveMinimum;\n }\n if ($this->exclusiveMaximum !== null) {\n $schema['exclusiveMaximum'] = $this->exclusiveMaximum;\n }\n if ($this->multipleOf !== null) {\n $schema['multipleOf'] = $this->multipleOf;\n }\n\n // Array\n if ($this->items !== null) {\n $schema['items'] = $this->items;\n }\n if ($this->minItems !== null) {\n $schema['minItems'] = $this->minItems;\n }\n if ($this->maxItems !== null) {\n $schema['maxItems'] = $this->maxItems;\n }\n if ($this->uniqueItems !== null) {\n $schema['uniqueItems'] = $this->uniqueItems;\n }\n\n // Object\n if ($this->properties !== null) {\n $schema['properties'] = $this->properties;\n }\n if ($this->required !== null) {\n $schema['required'] = $this->required;\n }\n if ($this->additionalProperties !== null) {\n $schema['additionalProperties'] = $this->additionalProperties;\n }\n\n return $schema;\n }\n}\n"], ["/server/src/Session/ArraySessionHandler.php", "\n */\n protected array $store = [];\n\n private ClockInterface $clock;\n\n public function __construct(\n public readonly int $ttl = 3600,\n ?ClockInterface $clock = null\n ) {\n $this->clock = $clock ?? new SystemClock();\n }\n\n public function read(string $sessionId): string|false\n {\n $session = $this->store[$sessionId] ?? '';\n if ($session === '') {\n return false;\n }\n\n $currentTimestamp = $this->clock->now()->getTimestamp();\n\n if ($currentTimestamp - $session['timestamp'] > $this->ttl) {\n unset($this->store[$sessionId]);\n return false;\n }\n\n return $session['data'];\n }\n\n public function write(string $sessionId, string $data): bool\n {\n $this->store[$sessionId] = [\n 'data' => $data,\n 'timestamp' => $this->clock->now()->getTimestamp(),\n ];\n\n return true;\n }\n\n public function destroy(string $sessionId): bool\n {\n if (isset($this->store[$sessionId])) {\n unset($this->store[$sessionId]);\n }\n\n return true;\n }\n\n public function gc(int $maxLifetime): array\n {\n $currentTimestamp = $this->clock->now()->getTimestamp();\n $deletedSessions = [];\n\n foreach ($this->store as $sessionId => $session) {\n if ($currentTimestamp - $session['timestamp'] > $maxLifetime) {\n unset($this->store[$sessionId]);\n $deletedSessions[] = $sessionId;\n }\n }\n\n return $deletedSessions;\n }\n}\n"], ["/server/src/Session/CacheSessionHandler.php", "sessionIndex = $this->cache->get(self::SESSION_INDEX_KEY, []);\n $this->clock = $clock ?? new SystemClock();\n }\n\n public function read(string $sessionId): string|false\n {\n $session = $this->cache->get($sessionId, false);\n if ($session === false) {\n if (isset($this->sessionIndex[$sessionId])) {\n unset($this->sessionIndex[$sessionId]);\n $this->cache->set(self::SESSION_INDEX_KEY, $this->sessionIndex);\n }\n return false;\n }\n\n if (!isset($this->sessionIndex[$sessionId])) {\n $this->sessionIndex[$sessionId] = $this->clock->now()->getTimestamp();\n $this->cache->set(self::SESSION_INDEX_KEY, $this->sessionIndex);\n return $session;\n }\n\n if ($this->clock->now()->getTimestamp() - $this->sessionIndex[$sessionId] > $this->ttl) {\n $this->cache->delete($sessionId);\n return false;\n }\n\n return $session;\n }\n\n public function write(string $sessionId, string $data): bool\n {\n $this->sessionIndex[$sessionId] = $this->clock->now()->getTimestamp();\n $this->cache->set(self::SESSION_INDEX_KEY, $this->sessionIndex);\n return $this->cache->set($sessionId, $data);\n }\n\n public function destroy(string $sessionId): bool\n {\n unset($this->sessionIndex[$sessionId]);\n $this->cache->set(self::SESSION_INDEX_KEY, $this->sessionIndex);\n return $this->cache->delete($sessionId);\n }\n\n public function gc(int $maxLifetime): array\n {\n $currentTime = $this->clock->now()->getTimestamp();\n $deletedSessions = [];\n\n foreach ($this->sessionIndex as $sessionId => $timestamp) {\n if ($currentTime - $timestamp > $maxLifetime) {\n $this->cache->delete($sessionId);\n unset($this->sessionIndex[$sessionId]);\n $deletedSessions[] = $sessionId;\n }\n }\n\n $this->cache->set(self::SESSION_INDEX_KEY, $this->sessionIndex);\n\n return $deletedSessions;\n }\n}\n"], ["/server/src/Defaults/InMemoryEventStore.php", "\n * Example: [eventId1 => ['streamId' => 'abc', 'message' => '...']]\n */\n private array $events = [];\n\n private function generateEventId(string $streamId): string\n {\n return $streamId . '_' . (int)(microtime(true) * 1000) . '_' . bin2hex(random_bytes(4));\n }\n\n private function getStreamIdFromEventId(string $eventId): ?string\n {\n $parts = explode('_', $eventId);\n return $parts[0] ?? null;\n }\n\n public function storeEvent(string $streamId, string $message): string\n {\n $eventId = $this->generateEventId($streamId);\n\n $this->events[$eventId] = [\n 'streamId' => $streamId,\n 'message' => $message,\n ];\n\n return $eventId;\n }\n\n public function replayEventsAfter(string $lastEventId, callable $sendCallback): void\n {\n if (!isset($this->events[$lastEventId])) {\n return;\n }\n\n $streamId = $this->getStreamIdFromEventId($lastEventId);\n if ($streamId === null) {\n return;\n }\n\n $foundLastEvent = false;\n\n // Sort by eventId for deterministic ordering\n ksort($this->events);\n\n foreach ($this->events as $eventId => ['streamId' => $eventStreamId, 'message' => $message]) {\n if ($eventStreamId !== $streamId) {\n continue;\n }\n\n if ($eventId === $lastEventId) {\n $foundLastEvent = true;\n continue;\n }\n\n if ($foundLastEvent) {\n $sendCallback($eventId, $message);\n }\n }\n }\n}\n"], ["/server/src/Defaults/ArrayCache.php", "has($key)) {\n return $default;\n }\n\n return $this->store[$key];\n }\n\n public function set(string $key, mixed $value, DateInterval|int|null $ttl = null): bool\n {\n $this->store[$key] = $value;\n $this->expiries[$key] = $this->calculateExpiry($ttl);\n\n return true;\n }\n\n public function delete(string $key): bool\n {\n unset($this->store[$key], $this->expiries[$key]);\n\n return true;\n }\n\n public function clear(): bool\n {\n $this->store = [];\n $this->expiries = [];\n\n return true;\n }\n\n public function getMultiple(iterable $keys, mixed $default = null): iterable\n {\n $result = [];\n foreach ($keys as $key) {\n $result[$key] = $this->get($key, $default);\n }\n\n return $result;\n }\n\n public function setMultiple(iterable $values, DateInterval|int|null $ttl = null): bool\n {\n $expiry = $this->calculateExpiry($ttl);\n foreach ($values as $key => $value) {\n $this->store[$key] = $value;\n $this->expiries[$key] = $expiry;\n }\n\n return true;\n }\n\n public function deleteMultiple(iterable $keys): bool\n {\n foreach ($keys as $key) {\n unset($this->store[$key], $this->expiries[$key]);\n }\n\n return true;\n }\n\n public function has(string $key): bool\n {\n if (! isset($this->store[$key])) {\n return false;\n }\n // Check expiry\n if (isset($this->expiries[$key]) && $this->expiries[$key] !== null && time() >= $this->expiries[$key]) {\n $this->delete($key);\n\n return false;\n }\n\n return true;\n }\n\n private function calculateExpiry(DateInterval|int|null $ttl): ?int\n {\n if ($ttl === null) {\n return null; // No expiry\n }\n if (is_int($ttl)) {\n return time() + $ttl;\n }\n if ($ttl instanceof DateInterval) {\n return (new DateTime())->add($ttl)->getTimestamp();\n }\n\n // Invalid TTL type, treat as no expiry\n return null;\n }\n}\n"], ["/server/src/Defaults/EnumCompletionProvider.php", "values = array_map(\n fn($case) => isset($case->value) && is_string($case->value) ? $case->value : $case->name,\n $enumClass::cases()\n );\n }\n\n public function getCompletions(string $currentValue, SessionInterface $session): array\n {\n if (empty($currentValue)) {\n return $this->values;\n }\n\n return array_values(array_filter(\n $this->values,\n fn(string $value) => str_starts_with($value, $currentValue)\n ));\n }\n}\n"], ["/server/src/Exception/ProtocolException.php", "code >= -32700 && $this->code <= -32600) ? $this->code : self::CODE_INVALID_REQUEST;\n\n return new JsonRpcError(\n jsonrpc: '2.0',\n id: $id,\n code: $code,\n message: $this->getMessage(),\n data: $this->getData()\n );\n }\n}\n"], ["/server/src/Defaults/ListCompletionProvider.php", "values;\n }\n\n return array_values(array_filter(\n $this->values,\n fn(string $value) => str_starts_with($value, $currentValue)\n ));\n }\n}\n"], ["/server/src/Contracts/ServerTransportInterface.php", " Resolves on successful send/queue, rejects on specific send error.\n */\n public function sendMessage(Message $message, string $sessionId, array $context = []): PromiseInterface;\n\n /**\n * Stops the transport listener gracefully and closes all active connections.\n * MUST eventually emit a 'close' event for the transport itself.\n * Individual client disconnects should emit 'client_disconnected' events.\n */\n public function close(): void;\n}\n"], ["/server/src/Attributes/CompletionProvider.php", "|null $providerClass \n * @param class-string|CompletionProviderInterface|null $provider If a class-string, it will be resolved from the container at the point of use.\n */\n public function __construct(\n public ?string $providerClass = null,\n public string|CompletionProviderInterface|null $provider = null,\n public ?array $values = null,\n public ?string $enum = null,\n ) {\n if (count(array_filter([$provider, $values, $enum])) !== 1) {\n throw new \\InvalidArgumentException('Only one of provider, values, or enum can be set');\n }\n }\n}\n"], ["/server/src/Exception/TransportException.php", "getMessage(),\n data: null\n );\n }\n}\n"], ["/server/src/Contracts/SessionHandlerInterface.php", "\n */\n public function dequeueMessages(): array;\n\n /**\n * Check if there are any messages in the queue.\n */\n public function hasQueuedMessages(): bool;\n\n /**\n * Get the session handler instance.\n *\n * @return SessionHandlerInterface\n */\n public function getHandler(): SessionHandlerInterface;\n}\n"], ["/server/src/Contracts/EventStoreInterface.php", "resource;\n } else {\n throw new \\RuntimeException(\n \"Mixed resource array contains invalid item type for URI '{$uri}': \" . \n (is_object($item) ? get_class($item) : gettype($item))\n );\n }\n }\n return $contents;\n[TASK_END]\n```", "inference_time": "2025-08-20 21-33-37"}, "editdistance_info": {"edit_distance": 35.7798, "calculate_time": "2025-08-20 21:33:37", "true_code_clean": "if ($hasResourceContents || $hasEmbeddedResource) {\n $result = [];\n foreach ($readResult as $item) {\n if ($item instanceof ResourceContents) {\n $result[] = $item;\n } elseif ($item instanceof EmbeddedResource) {\n $result[] = $item->resource;\n } else {\n $result = array_merge($result, $this->formatResult($item, $uri, $mimeType));\n }\n }\n return $result;\n }", "predict_code_clean": "$contents = [];\n foreach ($readResult as $item) {\n if ($item instanceof ResourceContents) {\n $contents[] = $item;\n } elseif ($item instanceof EmbeddedResource) {\n $contents[] = $item->resource;\n } else {\n throw new \\RuntimeException(\n \"Mixed resource array contains invalid item type for URI '{$uri}': \" . \n (is_object($item) ? get_class($item) : gettype($item))\n );\n }\n }\n return $contents;"}}