diff --git a/composer.json b/composer.json
index 8ed66c73..272c84d8 100644
--- a/composer.json
+++ b/composer.json
@@ -27,7 +27,7 @@
"ext-posix": "*",
"ctx/module-research": "^1.0",
"ctx/module-config-templates": "^1.0",
- "ctx/mcp-server": "^1.6.0",
+ "ctx/mcp-server": "^1.7.0",
"league/html-to-markdown": "^5.1",
"php-mcp/schema": "dev-main as 1.0",
"psr/log": "^3.0",
diff --git a/context.yaml b/context.yaml
index 379b54b5..44a6bfee 100644
--- a/context.yaml
+++ b/context.yaml
@@ -8,36 +8,60 @@ import:
- url: https://gist.githubusercontent.com/butschster/29e84fb9c976ac837181141f88049a35/raw/ed38539950f8c9c45ca8c67f9e026a837c97bc66/01-dev-prompts.yaml
type: url
+# context.yaml
+rag:
+ servers:
+ default:
+ driver: qdrant
+ endpoint_url: ${RAG_QDRANT_ENDPOINT:-http://qdrant.home.local}
+ api_key: ${RAG_QDRANT_API_KEY:-}
+ embeddings_dimension: 1536
+ embeddings_distance: Cosine
+
+ collections:
+ default:
+ server: default
+ collection: ${RAG_COLLECTION:-intruforce_knowledge}
+ description: "Project knowledge base"
+
+ vectorizer:
+ platform: openai
+ model: text-embedding-3-small
+ api_key: ${OPENAI_API_KEY}
+
+ transformer:
+ chunk_size: 1000
+ overlap: 200
+
tools:
- id: ctx-docs
- description: 'CTX docs'
- type: http
- schema:
- type: object
- properties:
- query:
- type: string
- description: "Question or task to get documentation for"
- requests:
- - url: "https://context7.com/api/v2/context"
- method: "GET"
- query:
- libraryId: "/context-hub/generator"
- type: "txt"
- query: "{{query}}"
+ name: CTX docs search
+ type: rag
+ description: |
+ Search the project knowledge base for documentation, code explanations, and insights.
+ Use this when you need to find previously stored information about the codebase.
+ collection: default
+ operations: [ search ]
projects:
- name: ctx-mcp-server
description: MCP server library
- name: ctx-docs
description: Docs for CTX
+ - name: mcp-schema
+ path: vendor/php-mcp/schema
+ description: PHP DTOs for the MCP specification
exclude:
patterns:
- ".env*"
+ - "*cache"
paths:
- ".claude"
- ".context"
+ - ".build"
+ - ".researches"
+ - "runtime"
documents:
- description: 'Project structure overview'
diff --git a/docs/example/config/rag-custom-tools.yaml b/docs/example/config/rag-custom-tools.yaml
new file mode 100644
index 00000000..88868d2d
--- /dev/null
+++ b/docs/example/config/rag-custom-tools.yaml
@@ -0,0 +1,102 @@
+# Custom RAG Tools Example
+#
+# Define AI-friendly tools with meaningful names and descriptions
+# that help the AI understand when and why to use each tool.
+
+rag:
+ servers:
+ default:
+ driver: qdrant
+ endpoint_url: ${RAG_QDRANT_ENDPOINT:-http://localhost:6333}
+
+ collections:
+ project-docs:
+ server: default
+ collection: project_documentation
+
+ architecture:
+ server: default
+ collection: architecture_decisions
+
+ conventions:
+ server: default
+ collection: coding_conventions
+
+ vectorizer:
+ platform: openai
+ model: text-embedding-3-small
+ api_key: ${OPENAI_API_KEY}
+
+# Custom RAG tools with meaningful names for AI
+tools:
+ # Documentation tools
+ - id: find-documentation
+ type: rag
+ description: |
+ Search project documentation for guides, tutorials, and how-to articles.
+ Use this when you need to understand:
+ - How to use a feature
+ - Setup instructions
+ - Configuration options
+ - Best practices for using the project
+ collection: project-docs
+ operations: [search]
+
+ - id: save-documentation
+ type: rag
+ description: |
+ Store documentation, guides, or explanations about project features.
+ Use this after discovering or documenting:
+ - How a feature works
+ - Setup procedures
+ - Configuration guides
+ collection: project-docs
+ operations: [store]
+
+ # Architecture tools
+ - id: understand-architecture
+ type: rag
+ description: |
+ Search architecture decisions and design patterns.
+ Use this when you need to understand:
+ - Why code is structured a certain way
+ - Design decisions and their rationale
+ - System boundaries and responsibilities
+ - Integration patterns between components
+ collection: architecture
+ operations: [search]
+
+ - id: document-architecture
+ type: rag
+ description: |
+ Store architecture decisions, patterns, and design rationale.
+ Use this after making or discovering:
+ - Important design decisions
+ - New patterns in the codebase
+ - System integration approaches
+ collection: architecture
+ operations: [store]
+
+ # Conventions tools
+ - id: check-conventions
+ type: rag
+ description: |
+ Search coding conventions and style guidelines.
+ Use this BEFORE writing code to ensure:
+ - Naming conventions are followed
+ - Code style matches project standards
+ - Patterns are consistent with existing code
+ collection: conventions
+ operations: [search]
+
+ - id: record-convention
+ type: rag
+ description: |
+ Store coding conventions and guidelines discovered in the codebase.
+ Use this when you identify:
+ - Naming patterns
+ - Code organization rules
+ - Testing conventions
+ - Documentation standards
+ collection: conventions
+ operations: [store]
diff --git a/docs/rag-tools/README.md b/docs/rag-tools/README.md
new file mode 100644
index 00000000..2dca476d
--- /dev/null
+++ b/docs/rag-tools/README.md
@@ -0,0 +1,300 @@
+# Feature Request: Configurable RAG Knowledge Stores with Custom Tools
+
+## Summary
+
+Refactor the RAG module to support multiple named storage configurations (servers + collections) and enable defining
+custom RAG tools via `context.yaml`. This improves AI understanding of tool purpose and allows project-specific
+knowledge stores with meaningful names and descriptions.
+
+## Problem Statement
+
+### Current Issues
+
+1. **Generic Tool Names**: Current tools (`rag-search`, `rag-store`) don't convey purpose to AI
+2. **Single Storage**: Only one Qdrant endpoint/collection per project
+3. **No Customization**: Tool descriptions are hardcoded, not project-specific
+4. **Tight Coupling**: Storage configuration mixed with feature toggle
+5. **CLI Limitations**: Commands don't support multi-collection operations
+
+### User Pain Points
+
+- AI doesn't understand when/why to use RAG tools
+- Can't use multiple knowledge bases (e.g., docs + architecture + team conventions)
+- Tool names like `rag-search` are meaningless to AI agents
+- No way to separate different knowledge domains
+
+---
+
+## Proposed Solution
+
+### New Configuration Schema
+
+```yaml
+# context.yaml
+
+rag:
+ # 1. Define RAG servers (connection settings)
+ servers:
+ default:
+ driver: qdrant
+ endpoint_url: ${RAG_QDRANT_ENDPOINT:-http://localhost:6333}
+ api_key: ${RAG_QDRANT_API_KEY:-} # optional
+
+ cloud:
+ driver: qdrant
+ endpoint_url: https://my-cluster.qdrant.io
+ api_key: ${QDRANT_CLOUD_API_KEY}
+
+ # 2. Define named collections (reference servers)
+ collections:
+ project-docs:
+ server: default # References server above
+ collection: intruforce_docs # Qdrant collection name
+ description: "Project documentation and guides"
+ # Optional per-collection overrides
+ embeddings_dimension: 1536
+ embeddings_distance: Cosine
+ transformer:
+ chunk_size: 1000
+ overlap: 200
+
+ architecture:
+ server: default
+ collection: intruforce_architecture
+ description: "Architecture decisions and patterns"
+ transformer:
+ chunk_size: 2000 # Larger chunks for architecture docs
+ overlap: 400
+
+ shared-knowledge:
+ server: cloud
+ collection: team_knowledge
+ description: "Shared team knowledge base"
+
+ # 3. Global vectorizer settings (shared by all collections)
+ vectorizer:
+ platform: openai
+ model: text-embedding-3-small
+ api_key: ${OPENAI_API_KEY}
+
+ # 4. Default transformer settings (can be overridden per collection)
+ transformer:
+ chunk_size: 1000
+ overlap: 200
+
+# 5. Define custom RAG tools
+tools:
+ - id: project-docs-search
+ name: find-docs # Optional: custom tool name (defaults to id)
+ type: rag
+ description: "Search project documentation for guides, tutorials, and how-to articles. Use this when you need to understand how to use project features."
+ collection: project-docs # Reference to named collection
+ operations: [ search ] # Available: search, store
+
+ - id: project-docs-store
+ type: rag
+ description: "Store project documentation and insights for future retrieval."
+ collection: project-docs
+ operations: [ store ]
+
+ - id: architecture-search
+ name: arch-search # Tool will be registered as "arch-search"
+ type: rag
+ description: "Search architecture decisions, patterns, and design rationale. Use when understanding why code is structured a certain way."
+ collection: architecture
+ operations: [ search ]
+
+ - id: team-knowledge-search
+ type: rag
+ description: "Search shared team knowledge including coding conventions and best practices."
+ collection: shared-knowledge
+ operations: [ search ]
+
+ - id: team-knowledge-store
+ type: rag
+ description: "Store shared team knowledge for the whole team to access."
+ collection: shared-knowledge
+ operations: [ store ]
+```
+
+### Tool Naming Convention
+
+For each collection with operations `[search, store]`, generate tools:
+
+- `{collection-id}-search` - Search tool
+- `{collection-id}-store` - Store tool
+
+### Generated Tool Schemas
+
+**Search Tool Schema:**
+
+```json
+{
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Search query in natural language"
+ },
+ "type": {
+ "type": "string",
+ "description": "Filter by type: architecture, api, testing, convention, tutorial, reference, general"
+ },
+ "sourcePath": {
+ "type": "string",
+ "description": "Filter by source path (exact or prefix match)"
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Maximum number of results to return",
+ "default": 10,
+ "minimum": 1,
+ "maximum": 50
+ }
+ },
+ "required": [
+ "query"
+ ]
+}
+```
+
+**Store Tool Schema:**
+
+```json
+{
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "string",
+ "description": "Content to store in the knowledge base"
+ },
+ "type": {
+ "type": "string",
+ "description": "Type: architecture, api, testing, convention, tutorial, reference, general",
+ "default": "general"
+ },
+ "sourcePath": {
+ "type": "string",
+ "description": "Source path (e.g., 'src/Auth/Service.php')"
+ },
+ "tags": {
+ "type": "string",
+ "description": "Tags (comma-separated)"
+ }
+ },
+ "required": [
+ "content"
+ ]
+}
+```
+
+---
+
+## CLI Commands Update
+
+All RAG commands will support `--collection` option:
+
+```bash
+# Index into specific collection
+ctx rag:index docs --collection=project-docs
+
+# Index into all collections (default behavior)
+ctx rag:index docs
+
+# Status for specific collection
+ctx rag:status --collection=architecture
+
+# Status for all collections
+ctx rag:status
+
+# Clear specific collection
+ctx rag:clear --collection=project-docs
+
+# Initialize specific collection
+ctx rag:init --collection=shared-knowledge
+
+# Reindex specific collection
+ctx rag:reindex docs --collection=project-docs
+```
+
+---
+
+## Backward Compatibility
+
+### Legacy Format Support
+
+The old format will continue to work and be internally converted:
+
+```yaml
+# LEGACY FORMAT (still supported)
+rag:
+ enabled: true
+ store:
+ driver: qdrant
+ qdrant:
+ endpoint_url: http://localhost:6333
+ collection: ctx_knowledge
+
+# Internally converts to:
+# servers: { default: { driver: qdrant, endpoint_url: ... } }
+# collections: { default: { server: default, collection: ctx_knowledge } }
+```
+
+### Detection Logic
+
+```php
+// In RagParserPlugin
+if (isset($data['store'])) {
+ // Legacy format - convert to new structure
+ return $this->convertLegacyFormat($data);
+}
+// New format with servers/collections
+return $this->parseNewFormat($data);
+```
+
+### Default Tools for Legacy Config
+
+When using legacy format without custom tools defined, automatically register:
+
+- `rag-search` (pointing to `default` collection)
+- `rag-store` (pointing to `default` collection)
+
+---
+
+## Benefits
+
+| Aspect | Before | After |
+|----------------------|------------------------|------------------------------------|
+| Tool naming | `rag-search` (generic) | `project-docs-search` (meaningful) |
+| AI understanding | Low | High (custom descriptions) |
+| Storage flexibility | 1 collection | Unlimited collections |
+| Configuration | Hardcoded | Declarative YAML |
+| Team sharing | Difficult | Easy (multiple servers) |
+| Knowledge separation | None | By domain/purpose |
+
+---
+
+## Implementation Stages
+
+See individual stage files for detailed implementation:
+
+1. **Stage 1**: Configuration Infrastructure (ServerConfig, CollectionConfig)
+2. **Stage 2**: Store Registry & Factory
+3. **Stage 3**: Service Layer Updates (collection-aware services)
+4. **Stage 4**: RAG Tool Type Support in Tool Parser
+5. **Stage 5**: Dynamic Tool Generation
+6. **Stage 6**: CLI Commands Update
+7. **Stage 7**: Integration & Testing
+
+---
+
+## Open Questions
+
+1. **Default Collection**: When no `--collection` specified in CLI, operate on all or require explicit choice?
+ - **Decision**: Operate on all collections by default, with clear output per collection
+
+2. **Tool Validation**: Fail at startup if referenced collection doesn't exist?
+ - **Decision**: Yes, fail early with clear error message
+
+3. **Collection Inheritance**: Should collections inherit from a "default" template?
+ - **Decision**: Collections inherit global `transformer` settings unless overridden
diff --git a/docs/rag-tools/developer-reference.md b/docs/rag-tools/developer-reference.md
new file mode 100644
index 00000000..91e4ef56
--- /dev/null
+++ b/docs/rag-tools/developer-reference.md
@@ -0,0 +1,568 @@
+# RAG Tools Feature - Developer Reference
+
+Quick reference to existing code patterns, files, and line numbers for implementing the RAG Knowledge Store feature.
+
+---
+
+## Project Structure
+
+```
+Main Project (ctx/generator)
+├── rag/ # RAG module (modify)
+│ ├── Config/ # Configuration classes
+│ ├── Console/ # CLI commands
+│ ├── MCP/Tools/ # MCP tool actions
+│ ├── Service/ # Business logic
+│ └── Store/ # Store factory
+
+ctx-mcp-server Project
+└── src/Tool/ # Tool infrastructure (reference)
+ ├── Config/ # ToolDefinition, ToolSchema
+ ├── Types/ # Tool handlers
+ └── ToolParserPlugin.php # Tool parsing
+```
+
+---
+
+## Configuration Classes
+
+### Current RAG Config Structure
+
+| File | Lines | Purpose |
+|------------------------------------|-------|----------------------------------------------------------|
+| `rag/Config/RagConfig.php` | 1-27 | Main config with enabled, store, vectorizer, transformer |
+| `rag/Config/StoreConfig.php` | 1-32 | Store settings (driver, endpoint, collection) |
+| `rag/Config/VectorizerConfig.php` | Full | Vectorizer settings (platform, model, api_key) |
+| `rag/Config/TransformerConfig.php` | Full | Chunking settings (chunk_size, overlap) |
+
+### Config Parsing Pattern
+
+```php
+// rag/Config/StoreConfig.php:17-28 - fromArray() pattern
+public static function fromArray(array $data): self
+{
+ $driver = (string) ($data['driver'] ?? 'qdrant');
+ $driverConfig = $data[$driver] ?? [];
+
+ return new self(
+ driver: $driver,
+ endpointUrl: (string) ($driverConfig['endpoint_url'] ?? 'http://localhost:6333'),
+ // ...
+ );
+}
+```
+
+### RagParserPlugin Pattern
+
+| File | Lines | Purpose |
+|---------------------------|-------|--------------------------------------------------|
+| `rag/RagParserPlugin.php` | 20-30 | `getConfigKey()` returns 'rag' |
+| `rag/RagParserPlugin.php` | 32-50 | `parse()` creates RagConfig and sets in registry |
+| `rag/RagParserPlugin.php` | 45-47 | Logging pattern after parse |
+
+```php
+// rag/RagParserPlugin.php:32-48
+public function parse(array $config, string $rootPath): ?RegistryInterface
+{
+ if (!$this->supports($config)) {
+ return null;
+ }
+
+ $ragConfig = RagConfig::fromArray($config['rag']);
+ $this->registry->setConfig($ragConfig);
+
+ $this->logger?->info('Parsed RAG configuration', [
+ 'enabled' => $ragConfig->enabled,
+ 'store_driver' => $ragConfig->store->driver,
+ ]);
+
+ return $this->registry;
+}
+```
+
+---
+
+## Registry Pattern
+
+### RagRegistry Implementation
+
+| File | Lines | Purpose |
+|--------------------------------|-------|---------------------------------|
+| `rag/RagRegistry.php` | 14-17 | Class definition with interface |
+| `rag/RagRegistry.php` | 21-34 | `setConfig()` and `isEnabled()` |
+| `rag/RagRegistry.php` | 36-45 | `getConfig()` with null check |
+| `rag/RagRegistryInterface.php` | Full | Interface contract |
+
+```php
+// rag/RagRegistry.php:17-45
+final class RagRegistry implements RagRegistryInterface
+{
+ private ?RagConfig $config = null;
+
+ public function __construct(
+ private readonly ?LoggerInterface $logger = null,
+ ) {}
+
+ public function setConfig(RagConfig $config): void
+ {
+ $this->config = $config;
+ $this->logger?->debug('RAG config set', ['enabled' => $config->enabled]);
+ }
+
+ public function isEnabled(): bool
+ {
+ return $this->config?->enabled ?? false;
+ }
+
+ public function getConfig(): RagConfig
+ {
+ if ($this->config === null) {
+ throw new \RuntimeException('RAG configuration not loaded');
+ }
+ return $this->config;
+ }
+}
+```
+
+---
+
+## Store & Factory
+
+### StoreFactory Pattern
+
+| File | Lines | Purpose |
+|------------------------------|-------|-----------------------------------|
+| `rag/Store/StoreFactory.php` | 12-16 | Constructor with VariableResolver |
+| `rag/Store/StoreFactory.php` | 18-35 | `create()` with match expression |
+| `rag/Store/StoreFactory.php` | 31-34 | Error handling for unknown driver |
+
+```php
+// rag/Store/StoreFactory.php:18-35
+public function create(RagConfig $config): StoreInterface
+{
+ return match ($config->store->driver) {
+ 'qdrant' => $this->createQdrantStore($config),
+ 'memory', 'in_memory' => new InMemoryStore(),
+ default => throw new \InvalidArgumentException(
+ \sprintf('Unknown RAG store driver: %s', $config->store->driver),
+ ),
+ };
+}
+```
+
+### Variable Resolution
+
+```php
+// rag/Store/StoreFactory.php - Variable resolution pattern
+$endpointUrl = $this->variableResolver->resolve($config->store->endpointUrl);
+$apiKey = $this->variableResolver->resolve($config->store->apiKey);
+```
+
+---
+
+## Service Layer
+
+### IndexerService
+
+| File | Lines | Purpose |
+|----------------------------------|-------|------------------------------------------|
+| `rag/Service/IndexerService.php` | 17-30 | Constructor creates TextSplitTransformer |
+| `rag/Service/IndexerService.php` | 32-47 | `index()` single document |
+| `rag/Service/IndexerService.php` | 49-73 | `indexBatch()` multiple documents |
+
+```php
+// rag/Service/IndexerService.php:17-30
+public function __construct(
+ private StoreInterface $store,
+ private VectorizerInterface $vectorizer,
+ private MetadataFactory $metadataFactory,
+ RagConfig $config,
+) {
+ $this->transformer = new TextSplitTransformer(
+ chunkSize: $config->transformer->chunkSize,
+ overlap: $config->transformer->overlap,
+ );
+}
+```
+
+### RetrieverService
+
+| File | Lines | Purpose |
+|------------------------------------|-------|-------------------------------|
+| `rag/Service/RetrieverService.php` | 13-19 | Constructor creates Retriever |
+| `rag/Service/RetrieverService.php` | 21-45 | `search()` with filters |
+| `rag/Service/RetrieverService.php` | 47-68 | `buildFilter()` for Qdrant |
+
+### SearchResultItem
+
+| File | Lines | Purpose |
+|------------------------------------|-------|--------------------------------|
+| `rag/Service/SearchResultItem.php` | 10-18 | Constructor with all fields |
+| `rag/Service/SearchResultItem.php` | 20-33 | `fromVectorDocument()` factory |
+| `rag/Service/SearchResultItem.php` | 35-47 | `format()` for output |
+
+---
+
+## MCP Tool Actions
+
+### Static Tool Pattern
+
+| File | Lines | Purpose |
+|-----------------------------------------------|-------|----------------------------------------------|
+| `rag/MCP/Tools/RagSearch/RagSearchAction.php` | 15-21 | Tool attribute with name, description, title |
+| `rag/MCP/Tools/RagSearch/RagSearchAction.php` | 22 | InputSchema attribute |
+| `rag/MCP/Tools/RagSearch/RagSearchAction.php` | 23-28 | Constructor with handler + logger |
+| `rag/MCP/Tools/RagSearch/RagSearchAction.php` | 30-42 | `__invoke()` method |
+
+```php
+// rag/MCP/Tools/RagSearch/RagSearchAction.php:15-42
+#[Tool(
+ name: 'rag-search',
+ description: 'Search the project knowledge base using natural language.',
+ title: 'RAG Search',
+)]
+#[InputSchema(class: RagSearchRequest::class)]
+final readonly class RagSearchAction
+{
+ public function __construct(
+ private RagSearchHandler $handler,
+ private LoggerInterface $logger,
+ ) {}
+
+ #[Post(path: '/tools/call/rag-search', name: 'tools.rag-search')]
+ public function __invoke(RagSearchRequest $request): CallToolResult
+ {
+ $this->logger->info('RAG Search', ['query' => $request->query]);
+
+ try {
+ return ToolResult::text($this->handler->handle($request));
+ } catch (\Throwable $e) {
+ $this->logger->error('RAG Search error', ['error' => $e->getMessage()]);
+ return ToolResult::error($e->getMessage());
+ }
+ }
+}
+```
+
+### Request DTO Pattern
+
+| File | Lines | Purpose |
+|----------------------------------------------------|-------|------------------------------------|
+| `rag/MCP/Tools/RagSearch/Dto/RagSearchRequest.php` | 10-22 | Request with Field attributes |
+| `rag/MCP/Tools/RagStore/Dto/RagStoreRequest.php` | 10-28 | Store request with getParsedTags() |
+
+```php
+// rag/MCP/Tools/RagSearch/Dto/RagSearchRequest.php:10-22
+final readonly class RagSearchRequest
+{
+ public function __construct(
+ #[Field(description: 'Search query in natural language')]
+ public string $query,
+ #[Field(description: 'Filter by type: architecture, api, ...')]
+ public ?string $type = null,
+ #[Field(description: 'Filter by source path')]
+ public ?string $sourcePath = null,
+ #[Field(description: 'Maximum number of results')]
+ #[Range(min: 1, max: 50)]
+ public int $limit = 10,
+ ) {}
+}
+```
+
+### Handler Pattern
+
+| File | Lines | Purpose |
+|------------------------------------------------|-------|-----------------------------------|
+| `rag/MCP/Tools/RagSearch/RagSearchHandler.php` | 12-17 | Constructor with RetrieverService |
+| `rag/MCP/Tools/RagSearch/RagSearchHandler.php` | 19-45 | `handle()` method |
+| `rag/MCP/Tools/RagStore/RagStoreHandler.php` | 12-17 | Constructor with IndexerService |
+| `rag/MCP/Tools/RagStore/RagStoreHandler.php` | 19-38 | `handle()` method |
+
+---
+
+## Tool Infrastructure (ctx-mcp-server)
+
+### ToolDefinition
+
+| File (ctx-mcp-server) | Lines | Purpose |
+|--------------------------------------|--------|---------------------------------|
+| `src/Tool/Config/ToolDefinition.php` | 11-26 | Constructor with all properties |
+| `src/Tool/Config/ToolDefinition.php` | 35-104 | `fromArray()` with validation |
+| `src/Tool/Config/ToolDefinition.php` | 48-55 | Extra fields extraction |
+| `src/Tool/Config/ToolDefinition.php` | 57-72 | Run type command parsing |
+| `src/Tool/Config/ToolDefinition.php` | 76-79 | HTTP type validation |
+
+```php
+// src/Tool/Config/ToolDefinition.php:48-55 (ctx-mcp-server)
+// Extract any extra configuration data (type-specific)
+$extra = [];
+$reservedKeys = ['id', 'description', 'type', 'commands', 'schema', 'env', 'workingDir'];
+foreach ($config as $key => $value) {
+ if (!\in_array($key, $reservedKeys, true)) {
+ $extra[$key] = $value;
+ }
+}
+```
+
+### ToolParserPlugin
+
+| File (ctx-mcp-server) | Lines | Purpose |
+|---------------------------------|-------|----------------------------------|
+| `src/Tool/ToolParserPlugin.php` | 18-20 | `getConfigKey()` returns 'tools' |
+| `src/Tool/ToolParserPlugin.php` | 22-56 | `parse()` iterates tools array |
+| `src/Tool/ToolParserPlugin.php` | 35-38 | Tool registration in registry |
+
+```php
+// src/Tool/ToolParserPlugin.php:22-56 (ctx-mcp-server)
+public function parse(array $config, string $rootPath): ?RegistryInterface
+{
+ if (!$this->supports($config)) {
+ return null;
+ }
+
+ foreach ($config['tools'] as $index => $toolConfig) {
+ try {
+ $tool = ToolDefinition::fromArray($toolConfig);
+ $this->toolRegistry->register($tool);
+ } catch (\Throwable $e) {
+ throw new \InvalidArgumentException(
+ \sprintf('Failed to parse tool at index %d: %s', $index, $e->getMessage()),
+ );
+ }
+ }
+
+ return $this->toolRegistry;
+}
+```
+
+### ToolRegistry
+
+| File (ctx-mcp-server) | Lines | Purpose |
+|-----------------------------|-------|------------------------------|
+| `src/Tool/ToolRegistry.php` | 14-17 | Class with interfaces |
+| `src/Tool/ToolRegistry.php` | 19-23 | `register()` method |
+| `src/Tool/ToolRegistry.php` | 25-34 | `get()` with existence check |
+| `src/Tool/ToolRegistry.php` | 36-44 | `has()` and `all()` methods |
+
+---
+
+## CLI Commands
+
+### Command Option Pattern
+
+| File | Lines | Purpose |
+|-----------------------------------|-------|-----------------------------|
+| `rag/Console/RagIndexCommand.php` | 28-32 | Argument definition |
+| `rag/Console/RagIndexCommand.php` | 34-47 | Option definitions |
+| `rag/Console/RagIndexCommand.php` | 49-53 | Config path and env options |
+
+```php
+// rag/Console/RagIndexCommand.php:28-53
+#[Argument(description: 'Directory path to index')]
+protected string $path;
+
+#[Option(shortcut: 'p', description: 'File pattern')]
+protected string $pattern = '*.md';
+
+#[Option(shortcut: 't', description: 'Document type')]
+protected string $type = 'general';
+
+#[Option(name: 'config-file', shortcut: 'c', description: 'Path to configuration file')]
+protected ?string $configPath = null;
+
+#[Option(name: 'env', shortcut: 'e', description: 'Path to .env file')]
+protected ?string $envFile = null;
+```
+
+### Scope Pattern for Config Loading
+
+| File | Lines | Purpose |
+|-----------------------------------|-------|-------------------------------------|
+| `rag/Console/RagIndexCommand.php` | 55-70 | Directories setup |
+| `rag/Console/RagIndexCommand.php` | 72-95 | Container scope with config loading |
+| `rag/Console/RagIndexCommand.php` | 80-90 | ConfigLoader creation |
+
+```php
+// rag/Console/RagIndexCommand.php:55-95 - Scope pattern
+$dirs = $dirs
+ ->determineRootPath($this->configPath)
+ ->withEnvFile($this->envFile);
+
+return $container->runScope(
+ bindings: new Scope(bindings: [DirectoriesInterface::class => $dirs]),
+ scope: function (
+ ConfigurationProvider $configProvider,
+ RagRegistryInterface $registry,
+ // ...
+ ): int {
+ // Load configuration
+ try {
+ $configLoader = $this->configPath !== null
+ ? $configProvider->fromPath($this->configPath)
+ : $configProvider->fromDefaultLocation();
+ $configLoader->load();
+ } catch (ConfigLoaderException $e) {
+ $this->output->error($e->getMessage());
+ return Command::FAILURE;
+ }
+
+ if (!$registry->isEnabled()) {
+ $this->output->error('RAG is not enabled');
+ return Command::FAILURE;
+ }
+
+ // ... command logic
+ },
+);
+```
+
+### Output Formatting
+
+| File | Lines | Purpose |
+|------------------------------------|---------|-----------------------------|
+| `rag/Console/RagStatusCommand.php` | 76-83 | Section and writeln pattern |
+| `rag/Console/RagIndexCommand.php` | 104-111 | Title and info display |
+| `rag/Console/RagIndexCommand.php` | 130-145 | ProgressBar usage |
+
+```php
+// Output patterns
+$this->output->title('RAG Index');
+$this->output->writeln(\sprintf('Path: %s', $this->path));
+$this->output->section('Store Configuration');
+$this->output->error('Error message');
+$this->output->success('Success message');
+$this->output->warning('Warning message');
+$this->output->note('Note message');
+```
+
+---
+
+## Bootloader Registration
+
+### RagBootloader
+
+| File | Lines | Purpose |
+|-------------------------|-------|-----------------------------|
+| `rag/RagBootloader.php` | 25-35 | `defineSingletons()` method |
+| `rag/RagBootloader.php` | 37-55 | Service registrations |
+
+```php
+// rag/RagBootloader.php - Registration pattern
+$container->bindSingleton(
+ RagRegistryInterface::class,
+ static fn(LoggerInterface $logger) => new RagRegistry($logger),
+);
+
+$container->bindSingleton(
+ StoreInterface::class,
+ static function (RagRegistryInterface $registry, StoreFactory $factory) {
+ return $factory->create($registry->getConfig());
+ },
+);
+```
+
+### ActionsBootloader RAG Registration
+
+| File | Lines | Purpose |
+|---------------------------------------|---------|------------------------------------|
+| `src/McpServer/ActionsBootloader.php` | 251-256 | RAG tools conditional registration |
+
+```php
+// src/McpServer/ActionsBootloader.php:251-256
+// RAG Tools - only if enabled in context.yaml
+if ($ragRegistry->isEnabled()) {
+ $actions[] = RagStoreAction::class;
+ $actions[] = RagSearchAction::class;
+ $actions[] = RagManageAction::class;
+}
+```
+
+---
+
+## JSON Schema
+
+### Tool Schema Location
+
+| File | Lines | Purpose |
+|--------------------|---------|----------------------------|
+| `json-schema.json` | 33-39 | Tools array definition |
+| `json-schema.json` | 490-569 | Tool definition |
+| `json-schema.json` | 505-512 | Tool type enum (run, http) |
+| `json-schema.json` | 540-568 | Conditional validation |
+
+### RAG Schema Location
+
+| File | Lines | Purpose |
+|--------------------|---------|---------------------------|
+| `json-schema.json` | 67-157 | RAG configuration |
+| `json-schema.json` | 76-117 | Store configuration |
+| `json-schema.json` | 119-138 | Vectorizer configuration |
+| `json-schema.json` | 140-155 | Transformer configuration |
+
+---
+
+## Test Patterns
+
+### Feature Test Pattern
+
+| File | Lines | Purpose |
+|-----------------------------------------------------------|-------|----------------------|
+| `tests/src/Feature/Console/GenerateCommand/ToolsTest.php` | 33-50 | Config file creation |
+| `tests/src/Feature/Console/GenerateCommand/ToolsTest.php` | 52-65 | Command assertion |
+
+```php
+// tests/src/Feature/Console/GenerateCommand/ToolsTest.php
+$configFile = $this->createTempFile(<<<'YAML'
+ tools:
+ - id: test-command
+ description: "A test tool"
+ type: run
+ commands:
+ - cmd: echo
+ args: ["hello"]
+ YAML
+);
+
+$this->assertCommandOutput(/* ... */);
+```
+
+---
+
+## Key Files Summary
+
+### Files to CREATE
+
+| Stage | File | Based On |
+|-------|-----------------------------------------|-----------------------------------------------|
+| 1 | `rag/Config/ServerConfig.php` | `rag/Config/StoreConfig.php` |
+| 1 | `rag/Config/CollectionConfig.php` | `rag/Config/StoreConfig.php` |
+| 2 | `rag/Store/StoreRegistryInterface.php` | `rag/RagRegistryInterface.php` |
+| 2 | `rag/Store/StoreRegistry.php` | `rag/RagRegistry.php` |
+| 3 | `rag/Service/ServiceFactory.php` | `rag/Store/StoreFactory.php` |
+| 4 | `rag/Tool/RagToolConfig.php` | `src/Tool/Config/ToolDefinition.php` |
+| 5 | `rag/Tool/RagToolRegistryInterface.php` | `rag/RagRegistryInterface.php` |
+| 5 | `rag/Tool/RagToolRegistry.php` | `src/Tool/ToolRegistry.php` |
+| 5 | `rag/Tool/DynamicRagSearchAction.php` | `rag/MCP/Tools/RagSearch/RagSearchAction.php` |
+| 5 | `rag/Tool/DynamicRagStoreAction.php` | `rag/MCP/Tools/RagStore/RagStoreAction.php` |
+| 5 | `rag/Tool/RagToolFactory.php` | `rag/Store/StoreFactory.php` |
+| 6 | `rag/Console/CollectionAwareTrait.php` | New |
+
+### Files to MODIFY
+
+| Stage | File | Changes |
+|-------|---------------------------------------------------|---------------------------------|
+| 1 | `rag/Config/RagConfig.php` | Add servers, collections arrays |
+| 1 | `rag/RagParserPlugin.php` | Legacy detection, new parsing |
+| 1 | `json-schema.json` | Add servers, collections schema |
+| 2 | `rag/Store/StoreFactory.php` | Add `createForCollection()` |
+| 2 | `rag/RagBootloader.php` | Register StoreRegistry |
+| 3 | `rag/Service/IndexerService.php` | Accept TransformerConfig |
+| 3 | `rag/MCP/Tools/RagStore/RagStoreHandler.php` | Use ServiceFactory |
+| 3 | `rag/MCP/Tools/RagSearch/RagSearchHandler.php` | Use ServiceFactory |
+| 4 | `src/Tool/Config/ToolDefinition.php` (mcp-server) | Add RAG validation |
+| 5 | `src/McpServer/ActionsBootloader.php` | Register dynamic tools |
+| 6 | `rag/Console/RagIndexCommand.php` | Add --collection |
+| 6 | `rag/Console/RagStatusCommand.php` | Add --collection |
+| 6 | `rag/Console/RagClearCommand.php` | Add --collection |
+| 6 | `rag/Console/RagInitCommand.php` | Add --collection |
+| 6 | `rag/Console/RagReindexCommand.php` | Add --collection |
diff --git a/docs/rag-tools/master-checklist.md b/docs/rag-tools/master-checklist.md
new file mode 100644
index 00000000..3155eb20
--- /dev/null
+++ b/docs/rag-tools/master-checklist.md
@@ -0,0 +1,228 @@
+# Feature: Configurable RAG Knowledge Stores with Custom Tools
+
+## Overview
+
+Refactor the RAG module to support multiple named storage configurations and custom RAG tools via `context.yaml`.
+Enables AI-friendly tool names, multiple knowledge bases, and project-specific configurations.
+
+## Stage Dependencies
+
+```
+Stage 1 (Config Infrastructure)
+ ↓
+Stage 2 (Store Registry)
+ ↓
+Stage 3 (Service Layer) → Stage 4 (Tool Parser)
+ ↓ ↓
+Stage 5 (Dynamic Tools) ←─────┘
+ ↓
+Stage 6 (CLI Commands)
+ ↓
+Stage 7 (Integration)
+```
+
+---
+
+## Development Progress
+
+### Stage 1: Configuration Infrastructure
+
+**Goal**: Create new config classes for servers and collections
+
+- [x] 1.1: Create `ServerConfig` class with driver, endpoint, apiKey, dimensions, distance
+- [x] 1.2: Create `CollectionConfig` class with server reference, collection name, description, transformer overrides
+- [x] 1.3: Update `RagConfig` to hold `servers`, `collections` arrays + global `vectorizer`, `transformer`
+- [x] 1.4: Update `RagParserPlugin` to parse new format with legacy fallback
+- [x] 1.5: Update JSON schema with new configuration structure
+- [ ] 1.6: Write unit tests for config parsing (new + legacy formats)
+
+**Notes**:
+- Created `ServerConfig` and `CollectionConfig` as readonly DTOs
+- `RagConfig::fromArray()` auto-detects legacy vs new format via presence of `store` key
+- Legacy format internally converts to new structure with `default` server/collection
+- Added `isLegacyFormat()`, `getServerForCollection()`, and collection helper methods
+
+**Status**: Completed (tests pending)
+**Completed**: 2025-01-22
+
+---
+
+### Stage 2: Store Registry & Factory
+
+**Goal**: Manage multiple store instances by collection name
+
+- [x] 2.1: Create `StoreRegistryInterface` with `getStore(collection)`, `hasCollection()`, `getCollectionConfig()`
+- [x] 2.2: Create `StoreRegistry` implementation with lazy store creation
+- [x] 2.3: Update `StoreFactory` to accept `ServerConfig` + `CollectionConfig`
+- [x] 2.4: Update `RagBootloader` to register `StoreRegistry` in container
+- [ ] 2.5: Write tests for multi-store management
+
+**Notes**:
+- `StoreRegistry` lazily creates and caches stores per collection
+- `StoreFactory::createForCollection()` added for new config structure
+- Legacy `StoreFactory::create()` preserved for backward compatibility
+- Updated `RagRegistry::jsonSerialize()` for new format
+
+**Status**: Completed (tests pending)
+**Completed**: 2025-01-22
+
+---
+
+### Stage 3: Service Layer Updates
+
+**Goal**: Make IndexerService and RetrieverService collection-aware
+
+- [x] 3.1: Create `ServiceFactory` for creating per-collection services
+- [x] 3.2: Update `IndexerService` constructor to accept collection-specific transformer config
+- [x] 3.3: Update `RetrieverService` constructor to accept collection-specific store
+- [x] 3.4: Update `RagStoreHandler` to use collection from tool config
+- [x] 3.5: Update `RagSearchHandler` to use collection from tool config
+- [ ] 3.6: Write tests for collection-specific service creation
+
+**Notes**:
+- `ServiceFactory` creates and caches indexers/retrievers per collection
+- Handlers now accept `ServiceFactory` + `collectionName` for flexibility
+- `withCollection()` method added to handlers for creating collection-specific instances
+- Legacy bindings in bootloader use first/default collection
+
+**Status**: Completed (tests pending)
+**Completed**: 2025-01-22
+
+---
+
+### Stage 4: RAG Tool Type Support
+
+**Goal**: Add `type: rag` parsing to tool infrastructure
+
+- [x] 4.1: Update `ToolDefinition::fromArray()` to recognize `type: rag`
+- [x] 4.2: Create `RagToolConfig` DTO for RAG-specific tool configuration
+- [ ] 4.3: Update JSON schema to include `type: rag` with `collection`, `operations` properties (skipped)
+- [x] 4.4: Add validation: fail if referenced collection doesn't exist
+- [ ] 4.5: Write tests for RAG tool parsing
+
+**Notes**:
+- `RagToolConfig` DTO with `fromArray()`, `hasSearch()`, `hasStore()` methods
+- `RagToolRegistry` and `RagToolRegistryInterface` for managing RAG tool configs
+- `RagToolParserPlugin` validates collection existence at parse time
+- JSON schema update skipped per user request
+
+**Status**: Completed (tests pending)
+**Completed**: 2025-01-22
+
+---
+
+### Stage 5: Dynamic Tool Generation
+
+**Goal**: Generate MCP tools from RAG tool configuration
+
+- [x] 5.1: Create `DynamicRagSearchAction` that accepts collection config at construction
+- [x] 5.2: Create `DynamicRagStoreAction` that accepts collection config at construction
+- [x] 5.3: Create `RagToolFactory` to build actions from `RagToolConfig`
+- [x] 5.4: Update `ActionsBootloader` to register dynamic RAG tools alongside static ones
+- [x] 5.5: Implement tool schema generation based on operations (search/store)
+- [ ] 5.6: Write integration tests for dynamic tool registration and execution
+
+**Notes**:
+- Dynamic actions use `ServiceFactory` for collection-specific services
+- `RagToolFactory::createAll()` returns arrays of search and store actions
+- `ActionsBootloader` registers dynamic tools via callback mechanism
+- Static tools still registered when no custom tools defined
+
+**Status**: Completed (tests pending)
+**Completed**: 2025-01-22
+
+---
+
+### Stage 6: CLI Commands Update
+
+**Goal**: Add `--collection` option to all RAG commands
+
+- [x] 6.1: Update `RagIndexCommand` with `--collection` option, iterate all if not specified
+- [x] 6.2: Update `RagStatusCommand` to show all collections or specific one
+- [x] 6.3: Update `RagClearCommand` with `--collection` option
+- [x] 6.4: Update `RagInitCommand` with `--collection` option
+- [x] 6.5: Update `RagReindexCommand` with `--collection` option
+- [x] 6.6: Add clear output formatting showing which collection is being operated on
+- [ ] 6.7: Write tests for CLI commands with collection parameter
+
+**Notes**:
+- Created `CollectionAwareTrait` with `--collection` option and helper methods
+- All commands iterate over collections with clear section headers
+- `getTargetCollections()` returns specified or all collections
+- Per-collection progress and statistics displayed
+
+**Status**: Completed (tests pending)
+**Completed**: 2025-01-22
+
+---
+
+### Stage 7: Integration & Testing
+
+**Goal**: End-to-end testing and documentation
+
+- [x] 7.1: Create example configuration files in `docs/example/config/`
+- [ ] 7.2: Write integration tests with multi-collection setup
+- [ ] 7.3: Test backward compatibility with legacy config format
+- [ ] 7.4: Update RAG documentation in VitePress
+- [ ] 7.5: Update developer reference guide
+- [ ] 7.6: Manual testing of complete workflow
+
+**Notes**:
+- Created `rag-multi-collection.yaml` and `rag-custom-tools.yaml` examples
+- Tests deferred per user request
+
+**Status**: In Progress
+**Completed**: Example configs created
+
+---
+
+## Codebase References
+
+### Configuration Parsing
+
+- `rag/RagParserPlugin.php` - Current RAG config parser (pattern to follow)
+- `rag/Config/RagConfig.php` - Current config structure
+- `rag/Config/StoreConfig.php` - Current store config
+- `src/McpServer/Tool/ToolParserPlugin.php` (ctx-mcp-server) - Tool parsing pattern
+
+### Store & Services
+
+- `rag/Store/StoreFactory.php` - Current store creation
+- `rag/Service/IndexerService.php` - Document indexing
+- `rag/Service/RetrieverService.php` - Document retrieval
+- `rag/RagBootloader.php` - Dependency injection setup
+
+### Tool Infrastructure (ctx-mcp-server)
+
+- `src/Tool/Config/ToolDefinition.php` - Tool config structure
+- `src/Tool/ToolRegistry.php` - Tool registration
+- `src/Tool/Types/` - Tool handler implementations
+
+### CLI Commands
+
+- `rag/Console/RagIndexCommand.php` - Index command pattern
+- `rag/Console/RagStatusCommand.php` - Status command pattern
+
+### MCP Actions
+
+- `rag/MCP/Tools/RagSearch/RagSearchAction.php` - Search tool pattern
+- `rag/MCP/Tools/RagStore/RagStoreAction.php` - Store tool pattern
+
+---
+
+## Usage Instructions
+
+⚠️ **Keep this checklist updated:**
+
+1. Mark completed substeps immediately with `[x]`
+2. Add notes about deviations or challenges after each stage
+3. Document decisions differing from plan
+4. Update status when starting/completing stages
+5. Record completion dates
+
+**Status Values:**
+
+- `Not Started` - Work hasn't begun
+- `In Progress` - Currently being implemented
+- `Blocked` - Waiting on something
+- `Completed` - All substeps done and verified
diff --git a/docs/rag-tools/stage-01-config-infrastructure.md b/docs/rag-tools/stage-01-config-infrastructure.md
new file mode 100644
index 00000000..02b5cec7
--- /dev/null
+++ b/docs/rag-tools/stage-01-config-infrastructure.md
@@ -0,0 +1,352 @@
+# Stage 1: Configuration Infrastructure
+
+## Overview
+
+Create the foundational configuration classes for the multi-server, multi-collection RAG architecture. This stage
+establishes the data structures that all subsequent stages will depend on, including backward compatibility with the
+legacy single-store format.
+
+## Files
+
+**CREATE:**
+
+- `rag/Config/ServerConfig.php` - Server connection settings (driver, endpoint, apiKey, dimensions, distance)
+- `rag/Config/CollectionConfig.php` - Named collection referencing a server with optional transformer overrides
+- `tests/src/Rag/Config/ServerConfigTest.php` - Unit tests for ServerConfig
+- `tests/src/Rag/Config/CollectionConfigTest.php` - Unit tests for CollectionConfig
+
+**MODIFY:**
+
+- `rag/Config/RagConfig.php` - Add servers/collections arrays, keep vectorizer/transformer as globals
+- `rag/RagParserPlugin.php` - Parse new format with legacy fallback detection
+- `json-schema.json` - Add new configuration schema structure
+
+## Code References
+
+### Pattern for Config Classes
+
+```php
+// rag/Config/StoreConfig.php:8-28 - Pattern for readonly config with fromArray()
+final readonly class StoreConfig
+{
+ public function __construct(
+ public string $driver = 'qdrant',
+ public string $endpointUrl = 'http://localhost:6333',
+ // ...
+ ) {}
+
+ public static function fromArray(array $data): self
+ {
+ // Parse with defaults
+ }
+}
+```
+
+### Pattern for Parser Plugin
+
+```php
+// rag/RagParserPlugin.php:20-48 - Pattern for parsing and registry update
+public function parse(array $config, string $rootPath): ?RegistryInterface
+{
+ if (!$this->supports($config)) {
+ return null;
+ }
+ // Parse config
+ $ragConfig = RagConfig::fromArray($config['rag']);
+ $this->registry->setConfig($ragConfig);
+ return $this->registry;
+}
+```
+
+## Implementation Details
+
+### 1. ServerConfig Class
+
+```php
+transformer ?? $fallback;
+ }
+}
+```
+
+### 3. Updated RagConfig Class
+
+```php
+ $servers
+ * @param array $collections
+ */
+ public function __construct(
+ public bool $enabled = false,
+ public array $servers = [],
+ public array $collections = [],
+ public VectorizerConfig $vectorizer = new VectorizerConfig(),
+ public TransformerConfig $transformer = new TransformerConfig(),
+ // Legacy support - kept for backward compatibility
+ public ?StoreConfig $store = null,
+ ) {}
+
+ public static function fromArray(array $data): self
+ {
+ // Detect legacy vs new format
+ if (isset($data['store'])) {
+ return self::fromLegacyArray($data);
+ }
+
+ return self::fromNewArray($data);
+ }
+
+ private static function fromLegacyArray(array $data): self
+ {
+ $storeConfig = StoreConfig::fromArray($data['store'] ?? []);
+
+ // Convert legacy to new structure
+ $serverConfig = new ServerConfig(
+ name: 'default',
+ driver: $storeConfig->driver,
+ endpointUrl: $storeConfig->endpointUrl,
+ apiKey: $storeConfig->apiKey,
+ embeddingsDimension: $storeConfig->embeddingsDimension,
+ embeddingsDistance: $storeConfig->embeddingsDistance,
+ );
+
+ $collectionConfig = new CollectionConfig(
+ name: 'default',
+ server: 'default',
+ collection: $storeConfig->collection,
+ );
+
+ return new self(
+ enabled: (bool) ($data['enabled'] ?? false),
+ servers: ['default' => $serverConfig],
+ collections: ['default' => $collectionConfig],
+ vectorizer: VectorizerConfig::fromArray($data['vectorizer'] ?? []),
+ transformer: TransformerConfig::fromArray($data['transformer'] ?? []),
+ store: $storeConfig, // Keep for backward compat
+ );
+ }
+
+ private static function fromNewArray(array $data): self
+ {
+ $servers = [];
+ foreach (($data['servers'] ?? []) as $name => $serverData) {
+ $servers[$name] = ServerConfig::fromArray($name, $serverData);
+ }
+
+ $collections = [];
+ foreach (($data['collections'] ?? []) as $name => $collectionData) {
+ $collections[$name] = CollectionConfig::fromArray($name, $collectionData);
+ }
+
+ return new self(
+ enabled: (bool) ($data['enabled'] ?? false),
+ servers: $servers,
+ collections: $collections,
+ vectorizer: VectorizerConfig::fromArray($data['vectorizer'] ?? []),
+ transformer: TransformerConfig::fromArray($data['transformer'] ?? []),
+ );
+ }
+
+ public function getServer(string $name): ServerConfig
+ {
+ if (!isset($this->servers[$name])) {
+ throw new \InvalidArgumentException(\sprintf('Server "%s" not found', $name));
+ }
+ return $this->servers[$name];
+ }
+
+ public function getCollection(string $name): CollectionConfig
+ {
+ if (!isset($this->collections[$name])) {
+ throw new \InvalidArgumentException(\sprintf('Collection "%s" not found', $name));
+ }
+ return $this->collections[$name];
+ }
+
+ public function hasCollection(string $name): bool
+ {
+ return isset($this->collections[$name]);
+ }
+
+ /**
+ * @return string[]
+ */
+ public function getCollectionNames(): array
+ {
+ return \array_keys($this->collections);
+ }
+}
+```
+
+### 4. JSON Schema Update
+
+Add to `json-schema.json` under `properties.rag.properties`:
+
+```json
+{
+ "servers": {
+ "type": "object",
+ "description": "Named server connections",
+ "additionalProperties": {
+ "type": "object",
+ "properties": {
+ "driver": {
+ "type": "string",
+ "enum": [
+ "qdrant",
+ "memory"
+ ],
+ "default": "qdrant"
+ },
+ "endpoint_url": {
+ "type": "string",
+ "default": "http://localhost:6333"
+ },
+ "api_key": {
+ "type": "string"
+ },
+ "embeddings_dimension": {
+ "type": "integer",
+ "default": 1536
+ },
+ "embeddings_distance": {
+ "type": "string",
+ "enum": [
+ "Cosine",
+ "Euclid",
+ "Dot"
+ ],
+ "default": "Cosine"
+ }
+ }
+ }
+ },
+ "collections": {
+ "type": "object",
+ "description": "Named collections referencing servers",
+ "additionalProperties": {
+ "type": "object",
+ "required": [
+ "server",
+ "collection"
+ ],
+ "properties": {
+ "server": {
+ "type": "string",
+ "description": "Reference to server name"
+ },
+ "collection": {
+ "type": "string",
+ "description": "Qdrant collection name"
+ },
+ "description": {
+ "type": "string"
+ },
+ "embeddings_dimension": {
+ "type": "integer"
+ },
+ "embeddings_distance": {
+ "type": "string"
+ },
+ "transformer": {
+ "$ref": "#/definitions/ragTransformer"
+ }
+ }
+ }
+ }
+}
+```
+
+## Definition of Done
+
+- [ ] `ServerConfig` class created with `fromArray()` static constructor
+- [ ] `CollectionConfig` class created with server reference and transformer override support
+- [ ] `RagConfig` updated to hold servers/collections maps
+- [ ] Legacy format detection works (`store` key triggers old parsing)
+- [ ] New format parsing works with validation
+- [ ] `RagConfig::getServer()`, `getCollection()`, `hasCollection()`, `getCollectionNames()` methods work
+- [ ] JSON schema updated with new structure
+- [ ] Unit tests pass for both legacy and new config formats
+- [ ] Existing RAG commands still work with legacy config
+
+## Dependencies
+
+**Requires**: None (foundation stage)
+**Enables**: Stage 2 (Store Registry), Stage 3 (Service Layer), Stage 4 (Tool Parser)
diff --git a/docs/rag-tools/stage-02-store-registry.md b/docs/rag-tools/stage-02-store-registry.md
new file mode 100644
index 00000000..450c1bd0
--- /dev/null
+++ b/docs/rag-tools/stage-02-store-registry.md
@@ -0,0 +1,351 @@
+# Stage 2: Store Registry & Factory
+
+## Overview
+
+Create a registry to manage multiple store instances, one per collection. The registry lazily creates stores on first
+access and caches them for reuse. The `StoreFactory` is updated to work with the new config structure.
+
+## Files
+
+**CREATE:**
+
+- `rag/Store/StoreRegistryInterface.php` - Interface for store management
+- `rag/Store/StoreRegistry.php` - Implementation with lazy store creation
+- `tests/src/Rag/Store/StoreRegistryTest.php` - Unit tests
+
+**MODIFY:**
+
+- `rag/Store/StoreFactory.php` - Accept ServerConfig + CollectionConfig instead of RagConfig
+- `rag/RagBootloader.php` - Register StoreRegistry in container
+
+## Code References
+
+### Pattern for Registry
+
+```php
+// rag/RagRegistry.php:14-50 - Pattern for config registry with interface
+final class RagRegistry implements RagRegistryInterface
+{
+ private ?RagConfig $config = null;
+
+ public function setConfig(RagConfig $config): void
+ {
+ $this->config = $config;
+ }
+
+ public function isEnabled(): bool
+ {
+ return $this->config?->enabled ?? false;
+ }
+}
+```
+
+### Pattern for Factory
+
+```php
+// rag/Store/StoreFactory.php:12-35 - Current factory pattern
+public function create(RagConfig $config): StoreInterface
+{
+ return match ($config->store->driver) {
+ 'qdrant' => new QdrantStore(/* ... */),
+ 'memory', 'in_memory' => new InMemoryStore(),
+ default => throw new \InvalidArgumentException(/* ... */),
+ };
+}
+```
+
+### Pattern for Bootloader Registration
+
+```php
+// rag/RagBootloader.php:30-45 - Pattern for singleton registration
+$container->bindSingleton(
+ RagRegistryInterface::class,
+ static fn() => new RagRegistry($logger),
+);
+```
+
+## Implementation Details
+
+### 1. StoreRegistryInterface
+
+```php
+ */
+ private array $stores = [];
+
+ public function __construct(
+ private readonly RagConfig $config,
+ private readonly StoreFactory $factory,
+ private readonly ?LoggerInterface $logger = null,
+ ) {}
+
+ public function getStore(string $collectionName): StoreInterface
+ {
+ if (!$this->hasCollection($collectionName)) {
+ throw new \InvalidArgumentException(
+ \sprintf('Collection "%s" not found in RAG configuration', $collectionName),
+ );
+ }
+
+ // Lazy creation with caching
+ if (!isset($this->stores[$collectionName])) {
+ $this->stores[$collectionName] = $this->createStore($collectionName);
+ }
+
+ return $this->stores[$collectionName];
+ }
+
+ public function hasCollection(string $collectionName): bool
+ {
+ return $this->config->hasCollection($collectionName);
+ }
+
+ public function getCollectionConfig(string $collectionName): CollectionConfig
+ {
+ return $this->config->getCollection($collectionName);
+ }
+
+ public function getCollectionNames(): array
+ {
+ return $this->config->getCollectionNames();
+ }
+
+ private function createStore(string $collectionName): StoreInterface
+ {
+ $collectionConfig = $this->config->getCollection($collectionName);
+ $serverConfig = $this->config->getServer($collectionConfig->server);
+
+ $this->logger?->debug('Creating store for collection', [
+ 'collection' => $collectionName,
+ 'server' => $collectionConfig->server,
+ 'driver' => $serverConfig->driver,
+ ]);
+
+ return $this->factory->createForCollection($serverConfig, $collectionConfig);
+ }
+}
+```
+
+### 3. Updated StoreFactory
+
+```php
+driver) {
+ 'qdrant' => $this->createQdrantStore($serverConfig, $collectionConfig),
+ 'memory', 'in_memory' => new InMemoryStore(),
+ default => throw new \InvalidArgumentException(
+ \sprintf('Unknown RAG store driver: %s', $serverConfig->driver),
+ ),
+ };
+ }
+
+ /**
+ * Legacy method for backward compatibility.
+ * @deprecated Use createForCollection() instead
+ */
+ public function create(RagConfig $config): StoreInterface
+ {
+ // Use default collection for legacy support
+ if (!empty($config->collections)) {
+ $collectionName = \array_key_first($config->collections);
+ $collectionConfig = $config->getCollection($collectionName);
+ $serverConfig = $config->getServer($collectionConfig->server);
+ return $this->createForCollection($serverConfig, $collectionConfig);
+ }
+
+ // Fallback to old store config if present
+ if ($config->store !== null) {
+ return $this->createFromLegacyConfig($config);
+ }
+
+ throw new \InvalidArgumentException('No collections or legacy store config found');
+ }
+
+ private function createQdrantStore(
+ ServerConfig $serverConfig,
+ CollectionConfig $collectionConfig,
+ ): QdrantStore {
+ $endpointUrl = $this->variableResolver->resolve($serverConfig->endpointUrl);
+ $apiKey = $this->variableResolver->resolve($serverConfig->apiKey);
+ $collectionName = $this->variableResolver->resolve($collectionConfig->collection);
+
+ // Use collection-level overrides or server defaults
+ $dimension = $collectionConfig->embeddingsDimension ?? $serverConfig->embeddingsDimension;
+ $distance = $collectionConfig->embeddingsDistance ?? $serverConfig->embeddingsDistance;
+
+ $parsedUrl = \parse_url($endpointUrl);
+ $host = $parsedUrl['host'] ?? 'localhost';
+ $port = $parsedUrl['port'] ?? 6333;
+ $scheme = $parsedUrl['scheme'] ?? 'http';
+ $isHttps = $scheme === 'https';
+
+ $qdrantConfig = new Config(
+ host: $host,
+ port: $port,
+ tls: $isHttps,
+ );
+
+ if ($apiKey !== '') {
+ $qdrantConfig->setApiKey($apiKey);
+ }
+
+ return new QdrantStore(
+ qdrant: new Qdrant(new GuzzleClient($qdrantConfig)),
+ collectionName: $collectionName,
+ vectorName: 'default',
+ vectorDimension: $dimension,
+ vectorDistance: $distance,
+ );
+ }
+
+ /**
+ * @deprecated Remove after full migration
+ */
+ private function createFromLegacyConfig(RagConfig $config): StoreInterface
+ {
+ $storeConfig = $config->store;
+ \assert($storeConfig !== null);
+
+ return match ($storeConfig->driver) {
+ 'qdrant' => $this->createQdrantStoreFromLegacy($storeConfig),
+ 'memory', 'in_memory' => new InMemoryStore(),
+ default => throw new \InvalidArgumentException(
+ \sprintf('Unknown RAG store driver: %s', $storeConfig->driver),
+ ),
+ };
+ }
+
+ private function createQdrantStoreFromLegacy(\Butschster\ContextGenerator\Rag\Config\StoreConfig $config): QdrantStore
+ {
+ // ... existing implementation from current StoreFactory
+ }
+}
+```
+
+### 4. Updated RagBootloader
+
+Add to `RagBootloader::defineSingletons()`:
+
+```php
+// Store registry for multi-collection support
+$container->bindSingleton(
+ StoreRegistryInterface::class,
+ static function (RagRegistryInterface $ragRegistry, StoreFactory $factory, LoggerInterface $logger) {
+ $config = $ragRegistry->getConfig();
+ return new StoreRegistry($config, $factory, $logger);
+ },
+);
+
+// Legacy StoreInterface binding - uses default collection
+$container->bindSingleton(
+ StoreInterface::class,
+ static function (StoreRegistryInterface $storeRegistry, RagRegistryInterface $ragRegistry) {
+ $collectionNames = $storeRegistry->getCollectionNames();
+ if (empty($collectionNames)) {
+ throw new \RuntimeException('No RAG collections configured');
+ }
+ // Use first collection as default for backward compatibility
+ return $storeRegistry->getStore($collectionNames[0]);
+ },
+);
+```
+
+## Definition of Done
+
+- [ ] `StoreRegistryInterface` created with all required methods
+- [ ] `StoreRegistry` implementation with lazy store creation and caching
+- [ ] `StoreFactory::createForCollection()` method works with new config structure
+- [ ] Legacy `StoreFactory::create()` method still works for backward compatibility
+- [ ] `StoreRegistry` registered in container via `RagBootloader`
+- [ ] Legacy `StoreInterface` binding uses default/first collection
+- [ ] Unit tests verify lazy creation and caching behavior
+- [ ] Multiple stores can be created for different collections
+
+## Dependencies
+
+**Requires**: Stage 1 (Configuration Infrastructure)
+**Enables**: Stage 3 (Service Layer), Stage 5 (Dynamic Tools)
diff --git a/docs/rag-tools/stage-03-service-layer.md b/docs/rag-tools/stage-03-service-layer.md
new file mode 100644
index 00000000..0dc0d4f4
--- /dev/null
+++ b/docs/rag-tools/stage-03-service-layer.md
@@ -0,0 +1,398 @@
+# Stage 3: Service Layer Updates
+
+## Overview
+
+Update `IndexerService` and `RetrieverService` to work with collection-specific configurations. Create a
+`ServiceFactory` that produces services configured for specific collections. Update existing handlers to accept
+collection context.
+
+## Files
+
+**CREATE:**
+
+- `rag/Service/ServiceFactory.php` - Factory for creating collection-specific services
+- `tests/src/Rag/Service/ServiceFactoryTest.php` - Unit tests
+
+**MODIFY:**
+
+- `rag/Service/IndexerService.php` - Accept TransformerConfig in constructor
+- `rag/Service/RetrieverService.php` - No changes needed (already accepts StoreInterface)
+- `rag/MCP/Tools/RagStore/RagStoreHandler.php` - Accept collection name parameter
+- `rag/MCP/Tools/RagSearch/RagSearchHandler.php` - Accept collection name parameter
+- `rag/RagBootloader.php` - Register ServiceFactory
+
+## Code References
+
+### Current IndexerService Constructor
+
+```php
+// rag/Service/IndexerService.php:17-30
+public function __construct(
+ private StoreInterface $store,
+ private VectorizerInterface $vectorizer,
+ private MetadataFactory $metadataFactory,
+ RagConfig $config,
+) {
+ $this->transformer = new TextSplitTransformer(
+ chunkSize: $config->transformer->chunkSize,
+ overlap: $config->transformer->overlap,
+ );
+}
+```
+
+### Current RetrieverService Constructor
+
+```php
+// rag/Service/RetrieverService.php:13-19
+public function __construct(
+ StoreInterface $store,
+ VectorizerInterface $vectorizer,
+) {
+ $this->retriever = new Retriever($vectorizer, $store);
+}
+```
+
+### Handler Pattern
+
+```php
+// rag/MCP/Tools/RagStore/RagStoreHandler.php:12-17
+public function __construct(
+ private IndexerService $indexer,
+) {}
+```
+
+## Implementation Details
+
+### 1. ServiceFactory
+
+```php
+ */
+ private array $indexers = [];
+
+ /** @var array */
+ private array $retrievers = [];
+
+ public function __construct(
+ private readonly RagConfig $config,
+ private readonly StoreRegistryInterface $storeRegistry,
+ private readonly VectorizerFactory $vectorizerFactory,
+ private readonly MetadataFactory $metadataFactory,
+ private readonly ?LoggerInterface $logger = null,
+ ) {}
+
+ /**
+ * Get IndexerService for a specific collection.
+ */
+ public function getIndexer(string $collectionName): IndexerService
+ {
+ if (!isset($this->indexers[$collectionName])) {
+ $this->indexers[$collectionName] = $this->createIndexer($collectionName);
+ }
+
+ return $this->indexers[$collectionName];
+ }
+
+ /**
+ * Get RetrieverService for a specific collection.
+ */
+ public function getRetriever(string $collectionName): RetrieverService
+ {
+ if (!isset($this->retrievers[$collectionName])) {
+ $this->retrievers[$collectionName] = $this->createRetriever($collectionName);
+ }
+
+ return $this->retrievers[$collectionName];
+ }
+
+ /**
+ * Get all collection names.
+ *
+ * @return string[]
+ */
+ public function getCollectionNames(): array
+ {
+ return $this->storeRegistry->getCollectionNames();
+ }
+
+ private function createIndexer(string $collectionName): IndexerService
+ {
+ $collectionConfig = $this->storeRegistry->getCollectionConfig($collectionName);
+ $transformerConfig = $collectionConfig->getTransformer($this->config->transformer);
+
+ $this->logger?->debug('Creating IndexerService', [
+ 'collection' => $collectionName,
+ 'chunk_size' => $transformerConfig->chunkSize,
+ 'overlap' => $transformerConfig->overlap,
+ ]);
+
+ return new IndexerService(
+ store: $this->storeRegistry->getStore($collectionName),
+ vectorizer: $this->getVectorizer(),
+ metadataFactory: $this->metadataFactory,
+ transformerConfig: $transformerConfig,
+ );
+ }
+
+ private function createRetriever(string $collectionName): RetrieverService
+ {
+ $this->logger?->debug('Creating RetrieverService', [
+ 'collection' => $collectionName,
+ ]);
+
+ return new RetrieverService(
+ store: $this->storeRegistry->getStore($collectionName),
+ vectorizer: $this->getVectorizer(),
+ );
+ }
+
+ private function getVectorizer(): VectorizerInterface
+ {
+ // Vectorizer is shared across all collections
+ if ($this->vectorizer === null) {
+ $this->vectorizer = $this->vectorizerFactory->create($this->config);
+ }
+
+ return $this->vectorizer;
+ }
+}
+```
+
+### 2. Updated IndexerService
+
+```php
+transformer = new TextSplitTransformer(
+ chunkSize: $transformerConfig->chunkSize,
+ overlap: $transformerConfig->overlap,
+ );
+ }
+
+ // ... rest of methods unchanged
+}
+```
+
+### 3. Updated RagStoreHandler
+
+```php
+content) === '') {
+ throw new \InvalidArgumentException('Content cannot be empty');
+ }
+
+ $type = DocumentType::tryFrom($request->type) ?? DocumentType::General;
+ $indexer = $this->serviceFactory->getIndexer($this->collectionName);
+
+ $result = $indexer->index(
+ content: $request->content,
+ type: $type,
+ sourcePath: $request->sourcePath,
+ tags: $request->getParsedTags(),
+ );
+
+ return \sprintf(
+ "Stored in knowledge base [%s].\nType: %s | Chunks: %d | Time: %.2fms",
+ $this->collectionName,
+ $type->value,
+ $result->chunksCreated,
+ $result->processingTimeMs,
+ );
+ }
+
+ /**
+ * Create handler for specific collection.
+ */
+ public function withCollection(string $collectionName): self
+ {
+ return new self($this->serviceFactory, $collectionName);
+ }
+}
+```
+
+### 4. Updated RagSearchHandler
+
+```php
+query) === '') {
+ throw new \InvalidArgumentException('Query cannot be empty');
+ }
+
+ $type = $request->type !== null ? DocumentType::tryFrom($request->type) : null;
+ $retriever = $this->serviceFactory->getRetriever($this->collectionName);
+
+ $results = $retriever->search(
+ query: $request->query,
+ limit: $request->limit,
+ type: $type,
+ sourcePath: $request->sourcePath,
+ );
+
+ if ($results === []) {
+ return \sprintf('No results found for "%s" in [%s]', $request->query, $this->collectionName);
+ }
+
+ $output = [\sprintf('Found %d results for "%s" in [%s]', \count($results), $request->query, $this->collectionName), ''];
+
+ foreach ($results as $i => $item) {
+ $output[] = \sprintf('--- Result %d ---', $i + 1);
+ $output[] = $item->format();
+ $output[] = '';
+ }
+
+ return \implode("\n", $output);
+ }
+
+ /**
+ * Create handler for specific collection.
+ */
+ public function withCollection(string $collectionName): self
+ {
+ return new self($this->serviceFactory, $collectionName);
+ }
+}
+```
+
+### 5. Updated RagBootloader
+
+Add to `RagBootloader::defineSingletons()`:
+
+```php
+// Service factory for multi-collection support
+$container->bindSingleton(
+ ServiceFactory::class,
+ static function (
+ RagRegistryInterface $ragRegistry,
+ StoreRegistryInterface $storeRegistry,
+ VectorizerFactory $vectorizerFactory,
+ MetadataFactory $metadataFactory,
+ LoggerInterface $logger,
+ ) {
+ return new ServiceFactory(
+ config: $ragRegistry->getConfig(),
+ storeRegistry: $storeRegistry,
+ vectorizerFactory: $vectorizerFactory,
+ metadataFactory: $metadataFactory,
+ logger: $logger,
+ );
+ },
+);
+
+// Legacy IndexerService binding - uses default collection
+$container->bindSingleton(
+ IndexerService::class,
+ static function (ServiceFactory $factory) {
+ $collectionNames = $factory->getCollectionNames();
+ if (empty($collectionNames)) {
+ throw new \RuntimeException('No RAG collections configured');
+ }
+ return $factory->getIndexer($collectionNames[0]);
+ },
+);
+
+// Legacy RetrieverService binding - uses default collection
+$container->bindSingleton(
+ RetrieverService::class,
+ static function (ServiceFactory $factory) {
+ $collectionNames = $factory->getCollectionNames();
+ if (empty($collectionNames)) {
+ throw new \RuntimeException('No RAG collections configured');
+ }
+ return $factory->getRetriever($collectionNames[0]);
+ },
+);
+```
+
+## Definition of Done
+
+- [ ] `ServiceFactory` created with `getIndexer()` and `getRetriever()` methods
+- [ ] Services are lazily created and cached per collection
+- [ ] `IndexerService` accepts `TransformerConfig` instead of full `RagConfig`
+- [ ] `RagStoreHandler` uses `ServiceFactory` with configurable collection
+- [ ] `RagSearchHandler` uses `ServiceFactory` with configurable collection
+- [ ] Both handlers have `withCollection()` method for creating collection-specific instances
+- [ ] `ServiceFactory` registered in container via `RagBootloader`
+- [ ] Legacy service bindings use default/first collection
+- [ ] Unit tests verify per-collection service creation
+- [ ] Existing RAG tools continue to work with legacy config
+
+## Dependencies
+
+**Requires**: Stage 1 (Configuration), Stage 2 (Store Registry)
+**Enables**: Stage 5 (Dynamic Tools), Stage 6 (CLI Commands)
diff --git a/docs/rag-tools/stage-04-tool-parser.md b/docs/rag-tools/stage-04-tool-parser.md
new file mode 100644
index 00000000..af2dfb83
--- /dev/null
+++ b/docs/rag-tools/stage-04-tool-parser.md
@@ -0,0 +1,301 @@
+# Stage 4: RAG Tool Type Support
+
+## Overview
+
+Extend the tool infrastructure to recognize `type: rag` tools in configuration. Create a `RagToolConfig` DTO to hold
+RAG-specific tool settings (collection, operations). Update the JSON schema and add validation.
+
+## Files
+
+**CREATE:**
+
+- `rag/Tool/RagToolConfig.php` - DTO for RAG tool configuration
+- `tests/src/Rag/Tool/RagToolConfigTest.php` - Unit tests
+
+**MODIFY:**
+
+- `src/Tool/Config/ToolDefinition.php` (ctx-mcp-server) - Add RAG tool type handling
+- `json-schema.json` - Add RAG tool schema with collection and operations
+
+## Code References
+
+### ToolDefinition Extra Handling
+
+```php
+// src/Tool/Config/ToolDefinition.php:48-55 (ctx-mcp-server)
+// Extract any extra configuration data (type-specific)
+$extra = [];
+$reservedKeys = ['id', 'description', 'type', 'commands', 'schema', 'env', 'workingDir'];
+foreach ($config as $key => $value) {
+ if (!\in_array($key, $reservedKeys, true)) {
+ $extra[$key] = $value;
+ }
+}
+```
+
+### HTTP Tool Validation Pattern
+
+```php
+// src/Tool/Config/ToolDefinition.php:76-79 (ctx-mcp-server)
+if ($type === 'http') {
+ if (!isset($config['requests']) || !\is_array($config['requests']) || empty($config['requests'])) {
+ throw new \InvalidArgumentException('HTTP tool must have a non-empty requests array');
+ }
+}
+```
+
+### JSON Schema Tool Type Enum
+
+```json
+// json-schema.json:505-512
+"type": {
+ "type": "string",
+ "enum": [
+ "run",
+ "http"
+ ],
+ "description": "Type of tool (run = command execution, http = HTTP requests)",
+ "default": "run"
+}
+```
+
+## Implementation Details
+
+### 1. RagToolConfig DTO
+
+```php
+validateOperations($operations);
+ }
+
+ public static function fromArray(array $data): self
+ {
+ if (empty($data['id']) || !\is_string($data['id'])) {
+ throw new \InvalidArgumentException('RAG tool must have a non-empty id');
+ }
+
+ if (empty($data['description']) || !\is_string($data['description'])) {
+ throw new \InvalidArgumentException('RAG tool must have a non-empty description');
+ }
+
+ if (empty($data['collection']) || !\is_string($data['collection'])) {
+ throw new \InvalidArgumentException('RAG tool must specify a collection');
+ }
+
+ $operations = $data['operations'] ?? [self::OPERATION_SEARCH, self::OPERATION_STORE];
+ if (!\is_array($operations)) {
+ throw new \InvalidArgumentException('RAG tool operations must be an array');
+ }
+
+ return new self(
+ id: $data['id'],
+ description: $data['description'],
+ collection: $data['collection'],
+ operations: $operations,
+ );
+ }
+
+ public function hasSearch(): bool
+ {
+ return \in_array(self::OPERATION_SEARCH, $this->operations, true);
+ }
+
+ public function hasStore(): bool
+ {
+ return \in_array(self::OPERATION_STORE, $this->operations, true);
+ }
+
+ /**
+ * Get the tool ID for search operation.
+ */
+ public function getSearchToolId(): string
+ {
+ return $this->id . '-search';
+ }
+
+ /**
+ * Get the tool ID for store operation.
+ */
+ public function getStoreToolId(): string
+ {
+ return $this->id . '-store';
+ }
+
+ private function validateOperations(array $operations): void
+ {
+ $valid = [self::OPERATION_SEARCH, self::OPERATION_STORE];
+
+ foreach ($operations as $op) {
+ if (!\in_array($op, $valid, true)) {
+ throw new \InvalidArgumentException(
+ \sprintf('Invalid RAG operation "%s". Valid: %s', $op, \implode(', ', $valid)),
+ );
+ }
+ }
+
+ if (empty($operations)) {
+ throw new \InvalidArgumentException('RAG tool must have at least one operation');
+ }
+ }
+}
+```
+
+### 2. Updated ToolDefinition (ctx-mcp-server)
+
+Add RAG tool validation after HTTP validation:
+
+```php
+// Add to ToolDefinition::fromArray() after HTTP validation
+
+// Handle 'rag' type specific validations
+if ($type === 'rag') {
+ if (!isset($config['collection']) || !\is_string($config['collection']) || $config['collection'] === '') {
+ throw new \InvalidArgumentException('RAG tool must specify a collection');
+ }
+
+ // Validate operations if provided
+ if (isset($config['operations'])) {
+ if (!\is_array($config['operations'])) {
+ throw new \InvalidArgumentException('RAG tool operations must be an array');
+ }
+
+ $validOps = ['search', 'store'];
+ foreach ($config['operations'] as $op) {
+ if (!\in_array($op, $validOps, true)) {
+ throw new \InvalidArgumentException(
+ \sprintf('Invalid RAG operation "%s". Valid: %s', $op, \implode(', ', $validOps)),
+ );
+ }
+ }
+ }
+}
+```
+
+Update the `$reservedKeys` array:
+
+```php
+$reservedKeys = ['id', 'description', 'type', 'commands', 'schema', 'env', 'workingDir', 'requests', 'collection', 'operations'];
+```
+
+### 3. JSON Schema Update
+
+Update `definitions.tool.properties.type`:
+
+```json
+"type": {
+ "type": "string",
+ "enum": [
+ "run",
+ "http",
+ "rag"
+ ],
+ "description": "Type of tool (run = command execution, http = HTTP requests, rag = RAG knowledge base)",
+ "default": "run"
+}
+```
+
+Add RAG-specific properties:
+
+```json
+"collection": {
+ "type": "string",
+ "description": "Reference to named RAG collection (for 'rag' type tools)"
+},
+"operations": {
+ "type": "array",
+ "description": "Available operations for RAG tool (for 'rag' type tools)",
+ "items": {
+ "type": "string",
+ "enum": ["search", "store"]
+ },
+ "default": ["search", "store"]
+}
+```
+
+Add conditional validation:
+
+```json
+{
+ "if": {
+ "properties": {
+ "type": {
+ "const": "rag"
+ }
+ }
+ },
+ "then": {
+ "required": ["collection"]
+ }
+}
+```
+
+### 4. Example Configuration
+
+After this stage, the following configuration will be valid:
+
+```yaml
+tools:
+ # Search-only tool
+ - id: project-docs
+ type: rag
+ description: "Search project documentation for guides and tutorials"
+ collection: project-docs
+ operations: [search]
+
+ # Store-only tool
+ - id: save-docs
+ type: rag
+ description: "Store documentation and insights"
+ collection: project-docs
+ operations: [store]
+
+ # Both operations (default)
+ - id: team-knowledge
+ type: rag
+ description: "Search and store team knowledge"
+ collection: shared-knowledge
+ operations: [search, store]
+```
+
+## Definition of Done
+
+- [ ] `RagToolConfig` DTO created with validation
+- [ ] `RagToolConfig::fromArray()` parses configuration correctly
+- [ ] `hasSearch()` and `hasStore()` methods work correctly
+- [ ] `getSearchToolId()` and `getStoreToolId()` return correct IDs
+- [ ] `ToolDefinition::fromArray()` validates RAG tool configuration
+- [ ] RAG tools stored in `extra` array with `collection` and `operations` keys
+- [ ] JSON schema updated with `type: rag` and related properties
+- [ ] Validation fails if `collection` is missing for RAG tools
+- [ ] Validation fails for invalid operations
+- [ ] Unit tests cover all validation scenarios
+
+## Dependencies
+
+**Requires**: Stage 1 (Configuration Infrastructure)
+**Enables**: Stage 5 (Dynamic Tool Generation)
diff --git a/docs/rag-tools/stage-05-dynamic-tools.md b/docs/rag-tools/stage-05-dynamic-tools.md
new file mode 100644
index 00000000..c1086e8e
--- /dev/null
+++ b/docs/rag-tools/stage-05-dynamic-tools.md
@@ -0,0 +1,518 @@
+# Stage 5: Dynamic Tool Generation
+
+## Overview
+
+Create dynamic MCP tool actions that are configured at runtime based on RAG tool definitions from `context.yaml`. The
+`RagToolFactory` creates action instances for each tool, and the `ActionsBootloader` registers them alongside static
+tools.
+
+## Files
+
+**CREATE:**
+
+- `rag/Tool/DynamicRagSearchAction.php` - Configurable search action
+- `rag/Tool/DynamicRagStoreAction.php` - Configurable store action
+- `rag/Tool/RagToolFactory.php` - Factory to build actions from config
+- `rag/Tool/RagToolRegistryInterface.php` - Interface for RAG tool registry
+- `rag/Tool/RagToolRegistry.php` - Registry for RAG tool configurations
+- `tests/src/Rag/Tool/RagToolFactoryTest.php` - Unit tests
+
+**MODIFY:**
+
+- `rag/RagParserPlugin.php` - Parse RAG tools and register in RagToolRegistry
+- `rag/RagBootloader.php` - Register RagToolFactory and RagToolRegistry
+- `src/McpServer/ActionsBootloader.php` - Register dynamic RAG tools
+
+## Code References
+
+### Static RAG Action Pattern
+
+```php
+// rag/MCP/Tools/RagSearch/RagSearchAction.php:15-21
+#[Tool(
+ name: 'rag-search',
+ description: 'Search the project knowledge base...',
+ title: 'RAG Search',
+)]
+#[InputSchema(class: RagSearchRequest::class)]
+final readonly class RagSearchAction
+```
+
+### ActionsBootloader Tool Registration
+
+```php
+// src/McpServer/ActionsBootloader.php:251-256
+// RAG Tools - only if enabled in context.yaml
+if ($ragRegistry->isEnabled()) {
+ $actions[] = RagStoreAction::class;
+ $actions[] = RagSearchAction::class;
+ $actions[] = RagManageAction::class;
+}
+```
+
+### Tool Handler Factory Pattern
+
+```php
+// src/Tool/ToolHandlerFactory.php (ctx-mcp-server)
+public function createHandlerForTool(ToolDefinition $tool): ToolHandlerInterface
+{
+ return match ($tool->type) {
+ 'run' => $this->container->get(RunToolHandler::class),
+ 'http' => $this->container->get(HttpToolHandler::class),
+ default => throw new \InvalidArgumentException(/* ... */),
+ };
+}
+```
+
+## Implementation Details
+
+### 1. RagToolRegistryInterface
+
+```php
+tools[$tool->id] = $tool;
+ }
+
+ public function all(): array
+ {
+ return \array_values($this->tools);
+ }
+
+ public function hasTools(): bool
+ {
+ return !empty($this->tools);
+ }
+}
+```
+
+### 3. DynamicRagSearchAction
+
+```php
+config->id;
+ }
+
+ public function getToolDescription(): string
+ {
+ return $this->config->description;
+ }
+
+ public function getToolTitle(): string
+ {
+ return \ucfirst(\str_replace('-', ' ', $this->config->id));
+ }
+
+ public function __invoke(RagSearchRequest $request): CallToolResult
+ {
+ $this->logger->info('Dynamic RAG Search', [
+ 'tool' => $this->config->id,
+ 'collection' => $this->config->collection,
+ 'query' => $request->query,
+ ]);
+
+ try {
+ $handler = new RagSearchHandler($this->serviceFactory, $this->config->collection);
+ return ToolResult::text($handler->handle($request));
+ } catch (\Throwable $e) {
+ $this->logger->error('Dynamic RAG Search error', [
+ 'tool' => $this->config->id,
+ 'error' => $e->getMessage(),
+ ]);
+ return ToolResult::error($e->getMessage());
+ }
+ }
+
+ /**
+ * Get JSON schema for this tool's input.
+ */
+ public function getInputSchema(): array
+ {
+ return [
+ 'type' => 'object',
+ 'properties' => [
+ 'query' => [
+ 'type' => 'string',
+ 'description' => 'Search query in natural language',
+ ],
+ 'type' => [
+ 'type' => 'string',
+ 'description' => 'Filter by type: architecture, api, testing, convention, tutorial, reference, general',
+ ],
+ 'sourcePath' => [
+ 'type' => 'string',
+ 'description' => 'Filter by source path (exact or prefix match)',
+ ],
+ 'limit' => [
+ 'type' => 'integer',
+ 'description' => 'Maximum number of results to return',
+ 'default' => 10,
+ 'minimum' => 1,
+ 'maximum' => 50,
+ ],
+ ],
+ 'required' => ['query'],
+ ];
+ }
+}
+```
+
+### 4. DynamicRagStoreAction
+
+```php
+config->id;
+ }
+
+ public function getToolDescription(): string
+ {
+ return $this->config->description;
+ }
+
+ public function getToolTitle(): string
+ {
+ return \ucfirst(\str_replace('-', ' ', $this->config->id));
+ }
+
+ public function __invoke(RagStoreRequest $request): CallToolResult
+ {
+ $this->logger->info('Dynamic RAG Store', [
+ 'tool' => $this->config->id,
+ 'collection' => $this->config->collection,
+ 'type' => $request->type,
+ ]);
+
+ try {
+ $handler = new RagStoreHandler($this->serviceFactory, $this->config->collection);
+ return ToolResult::text($handler->handle($request));
+ } catch (\Throwable $e) {
+ $this->logger->error('Dynamic RAG Store error', [
+ 'tool' => $this->config->id,
+ 'error' => $e->getMessage(),
+ ]);
+ return ToolResult::error($e->getMessage());
+ }
+ }
+
+ /**
+ * Get JSON schema for this tool's input.
+ */
+ public function getInputSchema(): array
+ {
+ return [
+ 'type' => 'object',
+ 'properties' => [
+ 'content' => [
+ 'type' => 'string',
+ 'description' => 'Content to store in the knowledge base',
+ ],
+ 'type' => [
+ 'type' => 'string',
+ 'description' => 'Type: architecture, api, testing, convention, tutorial, reference, general',
+ 'default' => 'general',
+ ],
+ 'sourcePath' => [
+ 'type' => 'string',
+ 'description' => 'Source path (e.g., "src/Auth/Service.php")',
+ ],
+ 'tags' => [
+ 'type' => 'string',
+ 'description' => 'Tags (comma-separated)',
+ ],
+ ],
+ 'required' => ['content'],
+ ];
+ }
+}
+```
+
+### 5. RagToolFactory
+
+```php
+toolRegistry->all() as $toolConfig) {
+ // Validate collection exists
+ if (!$this->ragRegistry->getConfig()->hasCollection($toolConfig->collection)) {
+ $this->logger->warning('RAG tool references non-existent collection', [
+ 'tool' => $toolConfig->id,
+ 'collection' => $toolConfig->collection,
+ ]);
+ continue;
+ }
+
+ if ($toolConfig->hasSearch()) {
+ $searchActions[] = $this->createSearchAction($toolConfig);
+ }
+
+ if ($toolConfig->hasStore()) {
+ $storeActions[] = $this->createStoreAction($toolConfig);
+ }
+ }
+
+ return [
+ 'search' => $searchActions,
+ 'store' => $storeActions,
+ ];
+ }
+
+ public function createSearchAction(RagToolConfig $config): DynamicRagSearchAction
+ {
+ return new DynamicRagSearchAction(
+ config: $config,
+ serviceFactory: $this->serviceFactory,
+ logger: $this->logger,
+ );
+ }
+
+ public function createStoreAction(RagToolConfig $config): DynamicRagStoreAction
+ {
+ return new DynamicRagStoreAction(
+ config: $config,
+ serviceFactory: $this->serviceFactory,
+ logger: $this->logger,
+ );
+ }
+}
+```
+
+### 6. Updated RagParserPlugin
+
+Add RAG tool parsing to handle tools defined alongside RAG configuration:
+
+```php
+// In RagParserPlugin::parse(), after setting RAG config
+
+// Check if there are RAG-type tools in the tools section
+if (isset($config['tools']) && \is_array($config['tools'])) {
+ foreach ($config['tools'] as $toolConfig) {
+ if (($toolConfig['type'] ?? '') === 'rag') {
+ try {
+ $ragTool = RagToolConfig::fromArray($toolConfig);
+
+ // Validate collection exists
+ if (!$ragConfig->hasCollection($ragTool->collection)) {
+ throw new \InvalidArgumentException(
+ \sprintf('RAG tool "%s" references non-existent collection "%s"', $ragTool->id, $ragTool->collection)
+ );
+ }
+
+ $this->toolRegistry->register($ragTool);
+ $this->logger?->debug('RAG tool registered', ['id' => $ragTool->id]);
+ } catch (\Throwable $e) {
+ $this->logger?->warning('Failed to parse RAG tool', ['error' => $e->getMessage()]);
+ throw $e;
+ }
+ }
+ }
+}
+```
+
+### 7. Updated ActionsBootloader
+
+Replace static RAG tool registration with dynamic:
+
+```php
+// src/McpServer/ActionsBootloader.php
+
+// In defineActions() method, replace static RAG tools registration:
+
+// RAG Tools - register dynamic tools from configuration
+if ($ragRegistry->isEnabled()) {
+ // Always include manage tool
+ $actions[] = RagManageAction::class;
+
+ // Check if custom RAG tools are defined
+ if ($container->has(RagToolRegistryInterface::class)) {
+ $ragToolRegistry = $container->get(RagToolRegistryInterface::class);
+
+ if ($ragToolRegistry->hasTools()) {
+ // Use dynamic tools from configuration
+ // These are registered separately via RagToolFactory
+ $this->logger->debug('Using dynamic RAG tools from configuration');
+ } else {
+ // Fallback to static tools if no custom tools defined
+ $actions[] = RagStoreAction::class;
+ $actions[] = RagSearchAction::class;
+ }
+ } else {
+ // Legacy: use static tools
+ $actions[] = RagStoreAction::class;
+ $actions[] = RagSearchAction::class;
+ }
+}
+```
+
+Also add dynamic tool registration:
+
+```php
+// Add method to register dynamic RAG tools in MCP registry
+private function registerDynamicRagTools(/* ... */): void
+{
+ $factory = $this->container->get(RagToolFactory::class);
+ $tools = $factory->createAll();
+
+ foreach ($tools['search'] as $action) {
+ // Register as MCP tool with custom name/description
+ $this->mcpRegistry->registerTool(
+ name: $action->getToolName(),
+ description: $action->getToolDescription(),
+ inputSchema: $action->getInputSchema(),
+ handler: $action(...),
+ );
+ }
+
+ foreach ($tools['store'] as $action) {
+ $this->mcpRegistry->registerTool(
+ name: $action->getToolName(),
+ description: $action->getToolDescription(),
+ inputSchema: $action->getInputSchema(),
+ handler: $action(...),
+ );
+ }
+}
+```
+
+## Definition of Done
+
+- [ ] `RagToolRegistryInterface` and `RagToolRegistry` created
+- [ ] `DynamicRagSearchAction` works with configurable collection and custom name/description
+- [ ] `DynamicRagStoreAction` works with configurable collection and custom name/description
+- [ ] `RagToolFactory` creates actions from all registered RAG tools
+- [ ] Factory validates collection existence before creating actions
+- [ ] `RagParserPlugin` registers RAG tools in `RagToolRegistry`
+- [ ] `ActionsBootloader` registers dynamic tools when custom RAG tools are defined
+- [ ] Fallback to static tools when no custom RAG tools configured
+- [ ] `RagManageAction` always registered when RAG is enabled
+- [ ] Dynamic tools have correct input schemas
+- [ ] Unit tests verify factory creates correct actions
+- [ ] Integration test verifies tools appear in MCP tool list
+
+## Dependencies
+
+**Requires**: Stage 3 (Service Layer), Stage 4 (Tool Parser)
+**Enables**: Stage 6 (CLI Commands), Stage 7 (Integration)
diff --git a/docs/rag-tools/stage-06-cli-commands.md b/docs/rag-tools/stage-06-cli-commands.md
new file mode 100644
index 00000000..39f19540
--- /dev/null
+++ b/docs/rag-tools/stage-06-cli-commands.md
@@ -0,0 +1,483 @@
+# Stage 6: CLI Commands Update
+
+## Overview
+
+Update all RAG CLI commands to support `--collection` option. When specified, operate on that collection only. When not
+specified, iterate over all collections with clear output per collection.
+
+## Files
+
+**MODIFY:**
+
+- `rag/Console/RagIndexCommand.php` - Add `--collection` option
+- `rag/Console/RagStatusCommand.php` - Add `--collection` option, show all or specific
+- `rag/Console/RagClearCommand.php` - Add `--collection` option
+- `rag/Console/RagInitCommand.php` - Add `--collection` option
+- `rag/Console/RagReindexCommand.php` - Add `--collection` option
+
+**CREATE:**
+
+- `tests/src/Rag/Console/RagIndexCommandTest.php` - Tests with collection parameter
+- `tests/src/Rag/Console/RagStatusCommandTest.php` - Tests for multi-collection output
+
+## Code References
+
+### Current Command Option Pattern
+
+```php
+// rag/Console/RagIndexCommand.php:35-41
+#[Option(shortcut: 'p', description: 'File pattern (e.g., "*.md", "*.txt")')]
+protected string $pattern = '*.md';
+
+#[Option(shortcut: 't', description: 'Document type: architecture, api, testing, convention, tutorial, reference, general')]
+protected string $type = 'general';
+```
+
+### Service Factory Access Pattern
+
+```php
+// rag/Console/RagIndexCommand.php:62-67
+// Get IndexerService after config is loaded
+$indexer = $container->get(IndexerService::class);
+```
+
+### Output Formatting Pattern
+
+```php
+// rag/Console/RagStatusCommand.php:76-83
+$this->output->section('Store Configuration');
+$this->output->writeln(\sprintf(' Driver: %s', $config->store->driver));
+```
+
+## Implementation Details
+
+### 1. Common Trait for Collection Option
+
+Create a shared trait to avoid duplication:
+
+```php
+getConfig();
+
+ if ($this->collection !== null) {
+ if (!$config->hasCollection($this->collection)) {
+ throw new \InvalidArgumentException(
+ \sprintf('Collection "%s" not found. Available: %s',
+ $this->collection,
+ \implode(', ', $config->getCollectionNames())
+ )
+ );
+ }
+ return [$this->collection];
+ }
+
+ return $config->getCollectionNames();
+ }
+
+ /**
+ * Output section header for collection operations.
+ */
+ protected function outputCollectionHeader(string $collectionName, string $operation): void
+ {
+ $this->output->section(\sprintf('%s: %s', $operation, $collectionName));
+ }
+}
+```
+
+### 2. Updated RagIndexCommand
+
+```php
+determineRootPath($this->configPath)
+ ->withEnvFile($this->envFile);
+
+ return $container->runScope(
+ bindings: new Scope(bindings: [DirectoriesInterface::class => $dirs]),
+ scope: function (
+ ConfigurationProvider $configProvider,
+ RagRegistryInterface $registry,
+ FileSystemLoader $loader,
+ DirectoriesInterface $dirs,
+ ServiceFactory $serviceFactory,
+ ): int {
+ // Load configuration
+ try {
+ $configLoader = $this->configPath !== null
+ ? $configProvider->fromPath($this->configPath)
+ : $configProvider->fromDefaultLocation();
+ $configLoader->load();
+ } catch (ConfigLoaderException $e) {
+ $this->output->error(\sprintf('Failed to load configuration: %s', $e->getMessage()));
+ return Command::FAILURE;
+ }
+
+ if (!$registry->isEnabled()) {
+ $this->output->error('RAG is not enabled in configuration');
+ return Command::FAILURE;
+ }
+
+ $fullPath = $dirs->getRootPath()->join($this->path)->toString();
+ if (!\is_dir($fullPath)) {
+ $this->output->error(\sprintf('Directory not found: %s', $this->path));
+ return Command::FAILURE;
+ }
+
+ // Get target collections
+ try {
+ $collections = $this->getTargetCollections($registry);
+ } catch (\InvalidArgumentException $e) {
+ $this->output->error($e->getMessage());
+ return Command::FAILURE;
+ }
+
+ $this->output->title('RAG Index');
+ $this->output->writeln(\sprintf('Path: %s', $this->path));
+ $this->output->writeln(\sprintf('Pattern: %s', $this->pattern));
+ $this->output->writeln(\sprintf('Type: %s', $this->type));
+ $this->output->writeln(\sprintf('Recursive: %s', $this->recursive ? 'Yes' : 'No'));
+ $this->output->writeln(\sprintf('Collections: %s', \implode(', ', $collections)));
+ $this->output->writeln('');
+
+ $total = $loader->count($fullPath, $this->pattern, $this->recursive);
+ if ($total === 0) {
+ $this->output->warning('No files found matching the pattern.');
+ return Command::SUCCESS;
+ }
+
+ $this->output->writeln(\sprintf('Found %d files', $total));
+ $docType = DocumentType::tryFrom($this->type) ?? DocumentType::General;
+
+ // Index into each collection
+ $overallChunks = 0;
+ $overallTime = 0.0;
+
+ foreach ($collections as $collectionName) {
+ $this->outputCollectionHeader($collectionName, 'Indexing');
+
+ $collectionConfig = $registry->getConfig()->getCollection($collectionName);
+ $this->output->writeln(\sprintf(' Target: %s', $collectionConfig->collection));
+
+ if ($this->dryRun) {
+ $this->output->note('Dry run - no changes made');
+ foreach ($loader->load($fullPath, $this->pattern, $this->recursive, $docType) as $doc) {
+ $this->output->writeln(\sprintf(' • %s', $doc->getMetadata()['source_path'] ?? 'unknown'));
+ }
+ continue;
+ }
+
+ $indexer = $serviceFactory->getIndexer($collectionName);
+ $progressBar = new ProgressBar($this->output, $total);
+ $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%');
+ $progressBar->start();
+
+ $totalChunks = 0;
+ $totalTime = 0.0;
+
+ foreach ($loader->load($fullPath, $this->pattern, $this->recursive, $docType) as $doc) {
+ $result = $indexer->indexBatch([$doc]);
+ $totalChunks += $result->chunksCreated;
+ $totalTime += $result->processingTimeMs;
+ $progressBar->advance();
+ }
+
+ $progressBar->finish();
+ $this->output->writeln('');
+ $this->output->writeln(\sprintf(
+ ' ✓ Indexed %d chunks in %.2fs',
+ $totalChunks,
+ $totalTime / 1000,
+ ));
+
+ $overallChunks += $totalChunks;
+ $overallTime += $totalTime;
+ }
+
+ if (!$this->dryRun) {
+ $this->output->writeln('');
+ $this->output->success(\sprintf(
+ 'Total: %d files → %d chunks across %d collection(s) (%.2fs)',
+ $total,
+ $overallChunks,
+ \count($collections),
+ $overallTime / 1000,
+ ));
+ }
+
+ return Command::SUCCESS;
+ },
+ );
+ }
+}
+```
+
+### 3. Updated RagStatusCommand
+
+```php
+getConfig();
+
+ if ($this->asJson) {
+ return $this->outputJson($config);
+ }
+
+ $this->output->title('RAG Knowledge Base Status');
+ $this->output->writeln(\sprintf('Enabled: %s', $config->enabled ? 'Yes' : 'No'));
+ $this->output->writeln('');
+
+ // Global Vectorizer
+ $this->output->section('Vectorizer Configuration');
+ $this->output->writeln(\sprintf(' Platform: %s', $config->vectorizer->platform));
+ $this->output->writeln(\sprintf(' Model: %s', $config->vectorizer->model));
+ $this->output->writeln('');
+
+ // Default Transformer
+ $this->output->section('Default Transformer');
+ $this->output->writeln(\sprintf(' Chunk Size: %d', $config->transformer->chunkSize));
+ $this->output->writeln(\sprintf(' Overlap: %d', $config->transformer->overlap));
+ $this->output->writeln('');
+
+ // Servers
+ $this->output->section('Servers');
+ foreach ($config->servers as $name => $server) {
+ $this->output->writeln(\sprintf(' %s:', $name));
+ $this->output->writeln(\sprintf(' Driver: %s', $server->driver));
+ $this->output->writeln(\sprintf(' Endpoint: %s', $server->endpointUrl));
+ $this->output->writeln(\sprintf(' Dimensions: %d', $server->embeddingsDimension));
+ $this->output->writeln('');
+ }
+
+ // Collections
+ try {
+ $collections = $this->getTargetCollections($registry);
+ } catch (\InvalidArgumentException $e) {
+ $this->output->error($e->getMessage());
+ return Command::FAILURE;
+ }
+
+ $this->output->section('Collections');
+ foreach ($collections as $name) {
+ $coll = $config->getCollection($name);
+ $this->output->writeln(\sprintf(' %s:', $name));
+ $this->output->writeln(\sprintf(' Server: %s', $coll->server));
+ $this->output->writeln(\sprintf(' Collection: %s', $coll->collection));
+ if ($coll->description !== null) {
+ $this->output->writeln(\sprintf(' Description: %s', $coll->description));
+ }
+ if ($coll->transformer !== null) {
+ $this->output->writeln(\sprintf(' Chunk Size: %d (override)', $coll->transformer->chunkSize));
+ $this->output->writeln(\sprintf(' Overlap: %d (override)', $coll->transformer->overlap));
+ }
+ $this->output->writeln('');
+ }
+
+ return Command::SUCCESS;
+ }
+}
+```
+
+### 4. Updated RagClearCommand
+
+```php
+// Add CollectionAwareTrait and --collection option
+// Modify to iterate over collections:
+
+foreach ($collections as $collectionName) {
+ $this->outputCollectionHeader($collectionName, 'Clearing');
+
+ $store = $storeRegistry->getStore($collectionName);
+
+ if (!$store instanceof ManagedStoreInterface) {
+ $this->output->writeln(' Store does not support clearing');
+ continue;
+ }
+
+ if (!$this->force) {
+ $confirm = $this->output->confirm(
+ \sprintf('Clear all entries in "%s"?', $collectionName),
+ false,
+ );
+ if (!$confirm) {
+ $this->output->writeln(' Skipped');
+ continue;
+ }
+ }
+
+ $this->output->write(' Clearing... ');
+ try {
+ $store->drop();
+ $store->setup();
+ $this->output->writeln('Done');
+ } catch (\Throwable $e) {
+ $this->output->writeln('Failed');
+ $this->output->error($e->getMessage());
+ }
+}
+```
+
+### 5. Updated RagInitCommand
+
+```php
+// Add CollectionAwareTrait and --collection option
+// Modify to iterate over collections:
+
+foreach ($collections as $collectionName) {
+ $this->outputCollectionHeader($collectionName, 'Initializing');
+
+ $collectionConfig = $config->getCollection($collectionName);
+ $serverConfig = $config->getServer($collectionConfig->server);
+
+ $this->output->writeln(\sprintf(' Server: %s', $collectionConfig->server));
+ $this->output->writeln(\sprintf(' Collection: %s', $collectionConfig->collection));
+
+ // ... rest of init logic per collection
+}
+```
+
+### 6. Updated RagReindexCommand
+
+```php
+// Add CollectionAwareTrait and --collection option
+// Similar pattern to RagIndexCommand, but clears first per collection
+```
+
+## Usage Examples
+
+```bash
+# Index into all collections
+ctx rag:index docs
+
+# Index into specific collection
+ctx rag:index docs --collection=project-docs
+
+# Status for all collections
+ctx rag:status
+
+# Status for specific collection
+ctx rag:status --collection=architecture
+
+# Clear specific collection
+ctx rag:clear --collection=project-docs
+
+# Initialize specific collection
+ctx rag:init --collection=shared-knowledge --force
+
+# Reindex specific collection
+ctx rag:reindex docs --collection=project-docs
+```
+
+## Definition of Done
+
+- [ ] `CollectionAwareTrait` created with `--collection` option and helper methods
+- [ ] All 5 RAG commands use the trait
+- [ ] `getTargetCollections()` returns specified collection or all collections
+- [ ] Clear error message when specified collection doesn't exist
+- [ ] Each command iterates over collections with clear output headers
+- [ ] `RagStatusCommand` shows servers, collections, and their configurations
+- [ ] `RagIndexCommand` reports per-collection and total statistics
+- [ ] `RagClearCommand` confirms per collection when not using `--force`
+- [ ] `RagInitCommand` initializes each collection separately
+- [ ] Commands work correctly with legacy single-collection config
+- [ ] Unit tests verify collection parameter handling
+
+## Dependencies
+
+**Requires**: Stage 2 (Store Registry), Stage 3 (Service Layer)
+**Enables**: Stage 7 (Integration Testing)
diff --git a/docs/rag-tools/stage-07-integration.md b/docs/rag-tools/stage-07-integration.md
new file mode 100644
index 00000000..4db0a471
--- /dev/null
+++ b/docs/rag-tools/stage-07-integration.md
@@ -0,0 +1,490 @@
+# Stage 7: Integration & Testing
+
+## Overview
+
+Final integration stage focusing on end-to-end testing, documentation updates, and example configurations. Verify
+backward compatibility and complete the feature implementation.
+
+## Files
+
+**CREATE:**
+
+- `docs/example/config/rag-multi-collection.yaml` - Example multi-collection config
+- `docs/example/config/rag-custom-tools.yaml` - Example with custom RAG tools
+- `tests/src/Feature/Rag/MultiCollectionIntegrationTest.php` - E2E tests
+- `tests/src/Feature/Rag/LegacyConfigCompatibilityTest.php` - Backward compat tests
+
+**MODIFY:**
+
+- `docs/rag-developer-reference.md` - Update with new configuration
+- `docs/example/config/rag-config.yaml` - Update with new options
+
+## Code References
+
+### Existing Example Config Pattern
+
+```yaml
+# docs/example/config/rag-config.yaml:17-38
+rag:
+ enabled: true
+ store:
+ driver: qdrant
+ qdrant:
+ endpoint_url: ${RAG_QDRANT_URL:-http://localhost:6333}
+ # ...
+```
+
+### Feature Test Pattern
+
+```php
+// tests/src/Feature/Console/GenerateCommand/ToolsTest.php:33-50
+$configFile = $this->createTempFile(<<<'YAML'
+ tools:
+ - id: test-command
+ description: "A test tool"
+ # ...
+ YAML
+);
+
+$this->assertCommandOutput(/* ... */);
+```
+
+## Implementation Details
+
+### 1. Example: Multi-Collection Configuration
+
+```yaml
+# docs/example/config/rag-multi-collection.yaml
+
+# Multi-Collection RAG Configuration Example
+#
+# This example demonstrates how to configure multiple RAG collections
+# for different knowledge domains within a project.
+#
+# Use cases:
+# - Separate documentation from architecture knowledge
+# - Keep team conventions in a shared cloud collection
+# - Different chunk sizes for different content types
+
+rag:
+ # Define server connections
+ servers:
+ local:
+ driver: qdrant
+ endpoint_url: ${RAG_LOCAL_ENDPOINT:-http://localhost:6333}
+ api_key: ${RAG_LOCAL_API_KEY:-}
+ embeddings_dimension: 1536
+ embeddings_distance: Cosine
+
+ cloud:
+ driver: qdrant
+ endpoint_url: ${RAG_CLOUD_ENDPOINT}
+ api_key: ${RAG_CLOUD_API_KEY}
+ embeddings_dimension: 1536
+ embeddings_distance: Cosine
+
+ # Define named collections
+ collections:
+ project-docs:
+ server: local
+ collection: ${PROJECT_NAME:-myproject}_docs
+ description: "Project documentation, guides, and tutorials"
+ # Use default transformer settings
+
+ architecture:
+ server: local
+ collection: ${PROJECT_NAME:-myproject}_architecture
+ description: "Architecture decisions, patterns, and design rationale"
+ transformer:
+ chunk_size: 2000 # Larger chunks for architecture docs
+ overlap: 400
+
+ api-specs:
+ server: local
+ collection: ${PROJECT_NAME:-myproject}_api
+ description: "API specifications and endpoint documentation"
+ transformer:
+ chunk_size: 500 # Smaller chunks for precise API matching
+ overlap: 100
+
+ team-knowledge:
+ server: cloud
+ collection: team_shared_knowledge
+ description: "Shared team knowledge, conventions, and best practices"
+
+ # Global vectorizer (shared by all collections)
+ vectorizer:
+ platform: openai
+ model: text-embedding-3-small
+ api_key: ${OPENAI_API_KEY}
+
+ # Default transformer (used when collection doesn't override)
+ transformer:
+ chunk_size: 1000
+ overlap: 200
+```
+
+### 2. Example: Custom RAG Tools Configuration
+
+```yaml
+# docs/example/config/rag-custom-tools.yaml
+
+# Custom RAG Tools Example
+#
+# Define AI-friendly tools with meaningful names and descriptions
+# that help the AI understand when and why to use each tool.
+
+rag:
+ servers:
+ default:
+ driver: qdrant
+ endpoint_url: ${RAG_QDRANT_ENDPOINT:-http://localhost:6333}
+
+ collections:
+ project-docs:
+ server: default
+ collection: project_documentation
+
+ architecture:
+ server: default
+ collection: architecture_decisions
+
+ conventions:
+ server: default
+ collection: coding_conventions
+
+# Custom RAG tools with meaningful names for AI
+tools:
+ # Documentation tools
+ - id: find-documentation
+ type: rag
+ description: |
+ Search project documentation for guides, tutorials, and how-to articles.
+ Use this when you need to understand:
+ - How to use a feature
+ - Setup instructions
+ - Configuration options
+ - Best practices for using the project
+ collection: project-docs
+ operations: [search]
+
+ - id: save-documentation
+ type: rag
+ description: |
+ Store documentation, guides, or explanations about project features.
+ Use this after discovering or documenting:
+ - How a feature works
+ - Setup procedures
+ - Configuration guides
+ collection: project-docs
+ operations: [store]
+
+ # Architecture tools
+ - id: understand-architecture
+ type: rag
+ description: |
+ Search architecture decisions and design patterns.
+ Use this when you need to understand:
+ - Why code is structured a certain way
+ - Design decisions and their rationale
+ - System boundaries and responsibilities
+ - Integration patterns between components
+ collection: architecture
+ operations: [search]
+
+ - id: document-architecture
+ type: rag
+ description: |
+ Store architecture decisions, patterns, and design rationale.
+ Use this after making or discovering:
+ - Important design decisions
+ - New patterns in the codebase
+ - System integration approaches
+ collection: architecture
+ operations: [store]
+
+ # Conventions tools
+ - id: check-conventions
+ type: rag
+ description: |
+ Search coding conventions and style guidelines.
+ Use this BEFORE writing code to ensure:
+ - Naming conventions are followed
+ - Code style matches project standards
+ - Patterns are consistent with existing code
+ collection: conventions
+ operations: [search]
+
+ - id: record-convention
+ type: rag
+ description: |
+ Store coding conventions and guidelines discovered in the codebase.
+ Use this when you identify:
+ - Naming patterns
+ - Code organization rules
+ - Testing conventions
+ - Documentation standards
+ collection: conventions
+ operations: [store]
+```
+
+### 3. Integration Test: Multi-Collection
+
+```php
+createTempFile(<<<'YAML'
+ rag:
+ servers:
+ default:
+ driver: memory
+ collections:
+ docs:
+ server: default
+ collection: test_docs
+ arch:
+ server: default
+ collection: test_arch
+ vectorizer:
+ platform: openai
+ model: text-embedding-3-small
+ api_key: test-key
+ YAML
+ );
+
+ $result = $this->runCommand('rag:status', ['--config-file' => $config]);
+
+ $this->assertStringContainsString('docs', $result);
+ $this->assertStringContainsString('arch', $result);
+ $this->assertStringContainsString('test_docs', $result);
+ $this->assertStringContainsString('test_arch', $result);
+ }
+
+ public function testIndexIntoSpecificCollection(): void
+ {
+ // Create config with multiple collections
+ $config = $this->createMultiCollectionConfig();
+
+ // Index into specific collection
+ $result = $this->runCommand('rag:index', [
+ 'path' => 'docs',
+ '--collection' => 'docs',
+ '--config-file' => $config,
+ '--dry-run' => true,
+ ]);
+
+ $this->assertStringContainsString('Indexing: docs', $result);
+ $this->assertStringNotContainsString('Indexing: arch', $result);
+ }
+
+ public function testIndexIntoAllCollections(): void
+ {
+ $config = $this->createMultiCollectionConfig();
+
+ $result = $this->runCommand('rag:index', [
+ 'path' => 'docs',
+ '--config-file' => $config,
+ '--dry-run' => true,
+ ]);
+
+ $this->assertStringContainsString('Indexing: docs', $result);
+ $this->assertStringContainsString('Indexing: arch', $result);
+ }
+
+ public function testInvalidCollectionNameFails(): void
+ {
+ $config = $this->createMultiCollectionConfig();
+
+ $result = $this->runCommand('rag:status', [
+ '--collection' => 'nonexistent',
+ '--config-file' => $config,
+ ]);
+
+ $this->assertStringContainsString('Collection "nonexistent" not found', $result);
+ }
+
+ public function testCustomRagToolsAreRegistered(): void
+ {
+ $config = $this->createTempFile(<<<'YAML'
+ rag:
+ servers:
+ default:
+ driver: memory
+ collections:
+ docs:
+ server: default
+ collection: test_docs
+ vectorizer:
+ platform: openai
+ api_key: test-key
+ tools:
+ - id: find-docs
+ type: rag
+ description: Search documentation
+ collection: docs
+ operations: [search]
+ YAML
+ );
+
+ $result = $this->runCommand('tool:list', ['--config-file' => $config]);
+
+ $this->assertStringContainsString('find-docs', $result);
+ $this->assertStringContainsString('Search documentation', $result);
+ }
+
+ private function createMultiCollectionConfig(): string
+ {
+ return $this->createTempFile(<<<'YAML'
+ rag:
+ servers:
+ default:
+ driver: memory
+ collections:
+ docs:
+ server: default
+ collection: test_docs
+ arch:
+ server: default
+ collection: test_arch
+ vectorizer:
+ platform: openai
+ api_key: test-key
+ YAML
+ );
+ }
+}
+```
+
+### 4. Legacy Compatibility Test
+
+```php
+createTempFile(<<<'YAML'
+ rag:
+ enabled: true
+ store:
+ driver: memory
+ memory:
+ collection: legacy_collection
+ vectorizer:
+ platform: openai
+ model: text-embedding-3-small
+ api_key: test-key
+ transformer:
+ chunk_size: 1000
+ overlap: 200
+ YAML
+ );
+
+ $result = $this->runCommand('rag:status', ['--config-file' => $config]);
+
+ $this->assertStringContainsString('Enabled: Yes', $result);
+ $this->assertStringContainsString('default', $result); // Converted collection name
+ }
+
+ public function testLegacyConfigWithDefaultTools(): void
+ {
+ $config = $this->createTempFile(<<<'YAML'
+ rag:
+ enabled: true
+ store:
+ driver: memory
+ vectorizer:
+ platform: openai
+ api_key: test-key
+ YAML
+ );
+
+ // When no custom RAG tools, static tools should be registered
+ $result = $this->runCommand('tool:list', ['--config-file' => $config]);
+
+ $this->assertStringContainsString('rag-search', $result);
+ $this->assertStringContainsString('rag-store', $result);
+ }
+
+ public function testMixedLegacyAndNewConfig(): void
+ {
+ // This should fail - can't mix store and servers/collections
+ $config = $this->createTempFile(<<<'YAML'
+ rag:
+ enabled: true
+ store:
+ driver: memory
+ servers:
+ default:
+ driver: memory
+ YAML
+ );
+
+ $result = $this->runCommand('rag:status', ['--config-file' => $config]);
+
+ // Should use legacy format when 'store' is present
+ $this->assertStringContainsString('default', $result);
+ }
+}
+```
+
+### 5. Documentation Updates
+
+Update `docs/rag-developer-reference.md` with:
+
+1. **New Configuration Format**
+ - Servers section explanation
+ - Collections section explanation
+ - Transformer overrides
+
+2. **Custom RAG Tools**
+ - How to define `type: rag` tools
+ - Operations (search, store)
+ - Tool naming conventions
+
+3. **CLI Commands**
+ - `--collection` option
+ - Multi-collection behavior
+
+4. **Migration Guide**
+ - How to migrate from legacy config
+ - Backward compatibility notes
+
+## Definition of Done
+
+- [ ] `rag-multi-collection.yaml` example created with comprehensive comments
+- [ ] `rag-custom-tools.yaml` example created with AI-friendly descriptions
+- [ ] Integration tests pass for multi-collection configuration
+- [ ] Integration tests pass for custom RAG tools
+- [ ] Legacy configuration format still works correctly
+- [ ] Static RAG tools (rag-search, rag-store) used when no custom tools defined
+- [ ] `docs/rag-developer-reference.md` updated with new features
+- [ ] Existing example configs updated or supplemented
+- [ ] All previous stage tests still pass
+- [ ] Manual end-to-end testing completed:
+ - [ ] Multi-collection indexing works
+ - [ ] Custom tools appear in MCP tool list
+ - [ ] CLI commands work with `--collection` option
+ - [ ] Legacy config works without changes
+
+## Dependencies
+
+**Requires**: All previous stages (1-6)
+**Enables**: Feature complete and ready for release
diff --git a/json-schema.json b/json-schema.json
index 8b026542..779fc02e 100644
--- a/json-schema.json
+++ b/json-schema.json
@@ -73,9 +73,89 @@
"default": false,
"description": "Enable RAG knowledge store"
},
+ "servers": {
+ "type": "object",
+ "description": "Named server connections for vector stores",
+ "additionalProperties": {
+ "type": "object",
+ "properties": {
+ "driver": {
+ "type": "string",
+ "enum": ["qdrant", "memory"],
+ "default": "qdrant",
+ "description": "Store backend driver"
+ },
+ "endpoint_url": {
+ "type": "string",
+ "default": "http://localhost:6333",
+ "description": "Server endpoint URL"
+ },
+ "api_key": {
+ "type": "string",
+ "description": "API key for authentication (optional for local instances)"
+ },
+ "embeddings_dimension": {
+ "type": "integer",
+ "default": 1536,
+ "description": "Vector embeddings dimension"
+ },
+ "embeddings_distance": {
+ "type": "string",
+ "enum": ["Cosine", "Euclid", "Dot"],
+ "default": "Cosine",
+ "description": "Distance metric for similarity search"
+ }
+ }
+ }
+ },
+ "collections": {
+ "type": "object",
+ "description": "Named collections referencing servers",
+ "additionalProperties": {
+ "type": "object",
+ "required": ["server", "collection"],
+ "properties": {
+ "server": {
+ "type": "string",
+ "description": "Reference to server name defined in servers section"
+ },
+ "collection": {
+ "type": "string",
+ "description": "Vector store collection name"
+ },
+ "description": {
+ "type": "string",
+ "description": "Human-readable description of the collection purpose"
+ },
+ "embeddings_dimension": {
+ "type": "integer",
+ "description": "Override server's embeddings dimension for this collection"
+ },
+ "embeddings_distance": {
+ "type": "string",
+ "enum": ["Cosine", "Euclid", "Dot"],
+ "description": "Override server's distance metric for this collection"
+ },
+ "transformer": {
+ "type": "object",
+ "description": "Override global transformer settings for this collection",
+ "properties": {
+ "chunk_size": {
+ "type": "integer",
+ "description": "Maximum chunk size in characters"
+ },
+ "overlap": {
+ "type": "integer",
+ "description": "Overlap between chunks in characters"
+ }
+ }
+ }
+ }
+ }
+ },
"store": {
"type": "object",
- "description": "Vector store configuration",
+ "description": "Vector store configuration (LEGACY - use servers/collections instead)",
"properties": {
"driver": {
"type": "string",
@@ -118,7 +198,7 @@
},
"vectorizer": {
"type": "object",
- "description": "Embedding/vectorizer configuration",
+ "description": "Embedding/vectorizer configuration (shared by all collections)",
"properties": {
"platform": {
"type": "string",
@@ -139,7 +219,7 @@
},
"transformer": {
"type": "object",
- "description": "Text chunking configuration",
+ "description": "Default text chunking configuration (can be overridden per collection)",
"properties": {
"chunk_size": {
"type": "integer",
@@ -506,9 +586,10 @@
"type": "string",
"enum": [
"run",
- "http"
+ "http",
+ "rag"
],
- "description": "Type of tool (run = command execution, http = HTTP requests)",
+ "description": "Type of tool (run = command execution, http = HTTP requests, rag = RAG knowledge base)",
"default": "run"
},
"schema": {
@@ -535,6 +616,19 @@
"items": {
"$ref": "#/definitions/httpRequest"
}
+ },
+ "collection": {
+ "type": "string",
+ "description": "Reference to named RAG collection (for 'rag' type tools)"
+ },
+ "operations": {
+ "type": "array",
+ "description": "Available operations for RAG tool (for 'rag' type tools)",
+ "items": {
+ "type": "string",
+ "enum": ["search", "store"]
+ },
+ "default": ["search", "store"]
}
},
"allOf": [
@@ -565,6 +659,20 @@
"requests"
]
}
+ },
+ {
+ "if": {
+ "properties": {
+ "type": {
+ "const": "rag"
+ }
+ }
+ },
+ "then": {
+ "required": [
+ "collection"
+ ]
+ }
}
]
},
diff --git a/rag/Config/CollectionConfig.php b/rag/Config/CollectionConfig.php
new file mode 100644
index 00000000..14119333
--- /dev/null
+++ b/rag/Config/CollectionConfig.php
@@ -0,0 +1,64 @@
+transformer ?? $fallback;
+ }
+
+ /**
+ * Get effective embeddings dimension (collection override or fallback to server).
+ */
+ public function getEffectiveEmbeddingsDimension(ServerConfig $server): int
+ {
+ return $this->embeddingsDimension ?? $server->embeddingsDimension;
+ }
+
+ /**
+ * Get effective embeddings distance (collection override or fallback to server).
+ */
+ public function getEffectiveEmbeddingsDistance(ServerConfig $server): string
+ {
+ return $this->embeddingsDistance ?? $server->embeddingsDistance;
+ }
+}
diff --git a/rag/Config/RagConfig.php b/rag/Config/RagConfig.php
index 81847b2c..230f266d 100644
--- a/rag/Config/RagConfig.php
+++ b/rag/Config/RagConfig.php
@@ -4,20 +4,173 @@
namespace Butschster\ContextGenerator\Rag\Config;
+/**
+ * Root configuration for the RAG module.
+ *
+ * Supports two formats:
+ * - Legacy format: single `store` with driver-specific config
+ * - New format: multiple `servers` and `collections`
+ *
+ * Legacy format is automatically converted to new format for internal use.
+ */
final readonly class RagConfig
{
+ /**
+ * @param array $servers Named server configurations
+ * @param array $collections Named collection configurations
+ * @param StoreConfig|null $store Legacy store config (for backward compatibility)
+ */
public function __construct(
public bool $enabled = false,
- public StoreConfig $store = new StoreConfig(),
+ public array $servers = [],
+ public array $collections = [],
public VectorizerConfig $vectorizer = new VectorizerConfig(),
public TransformerConfig $transformer = new TransformerConfig(),
+ public ?StoreConfig $store = null,
) {}
public static function fromArray(array $data): self
{
+ if (isset($data['store'])) {
+ return self::fromLegacyArray($data);
+ }
+
+ return self::fromNewArray($data);
+ }
+
+ /**
+ * Check if configuration uses legacy format.
+ */
+ public function isLegacyFormat(): bool
+ {
+ return $this->store !== null;
+ }
+
+ /**
+ * Get server by name.
+ *
+ * @throws \InvalidArgumentException If server not found
+ */
+ public function getServer(string $name): ServerConfig
+ {
+ if (!isset($this->servers[$name])) {
+ throw new \InvalidArgumentException(\sprintf('Server "%s" not found', $name));
+ }
+
+ return $this->servers[$name];
+ }
+
+ /**
+ * Get collection by name.
+ *
+ * @throws \InvalidArgumentException If collection not found
+ */
+ public function getCollection(string $name): CollectionConfig
+ {
+ if (!isset($this->collections[$name])) {
+ throw new \InvalidArgumentException(\sprintf('Collection "%s" not found', $name));
+ }
+
+ return $this->collections[$name];
+ }
+
+ /**
+ * Check if collection exists.
+ */
+ public function hasCollection(string $name): bool
+ {
+ return isset($this->collections[$name]);
+ }
+
+ /**
+ * Get all collection names.
+ *
+ * @return string[]
+ */
+ public function getCollectionNames(): array
+ {
+ return \array_keys($this->collections);
+ }
+
+ /**
+ * Get all server names.
+ *
+ * @return string[]
+ */
+ public function getServerNames(): array
+ {
+ return \array_keys($this->servers);
+ }
+
+ /**
+ * Get server for a given collection.
+ *
+ * @throws \InvalidArgumentException If collection or server not found
+ */
+ public function getServerForCollection(string $collectionName): ServerConfig
+ {
+ $collection = $this->getCollection($collectionName);
+
+ return $this->getServer($collection->server);
+ }
+
+ /**
+ * Convert legacy format (single store) to new multi-server/collection format.
+ */
+ private static function fromLegacyArray(array $data): self
+ {
+ $storeConfig = StoreConfig::fromArray($data['store'] ?? []);
+
+ $serverConfig = new ServerConfig(
+ name: 'default',
+ driver: $storeConfig->driver,
+ endpointUrl: $storeConfig->endpointUrl,
+ apiKey: $storeConfig->apiKey,
+ embeddingsDimension: $storeConfig->embeddingsDimension,
+ embeddingsDistance: $storeConfig->embeddingsDistance,
+ );
+
+ $collectionConfig = new CollectionConfig(
+ name: 'default',
+ server: 'default',
+ collection: $storeConfig->collection,
+ );
+
return new self(
enabled: (bool) ($data['enabled'] ?? false),
- store: StoreConfig::fromArray($data['store'] ?? []),
+ servers: ['default' => $serverConfig],
+ collections: ['default' => $collectionConfig],
+ vectorizer: VectorizerConfig::fromArray($data['vectorizer'] ?? []),
+ transformer: TransformerConfig::fromArray($data['transformer'] ?? []),
+ store: $storeConfig,
+ );
+ }
+
+ /**
+ * Parse new format with explicit servers and collections.
+ */
+ private static function fromNewArray(array $data): self
+ {
+ $servers = [];
+ foreach (($data['servers'] ?? []) as $name => $serverData) {
+ $servers[$name] = ServerConfig::fromArray((string) $name, $serverData);
+ }
+
+ $collections = [];
+ foreach (($data['collections'] ?? []) as $name => $collectionData) {
+ $collections[$name] = CollectionConfig::fromArray((string) $name, $collectionData);
+ }
+
+ // If servers/collections are defined, ensure at least RAG is considered "configured"
+ $enabled = (bool) ($data['enabled'] ?? false);
+ if (!$enabled && (!empty($servers) || !empty($collections))) {
+ $enabled = true;
+ }
+
+ return new self(
+ enabled: $enabled,
+ servers: $servers,
+ collections: $collections,
vectorizer: VectorizerConfig::fromArray($data['vectorizer'] ?? []),
transformer: TransformerConfig::fromArray($data['transformer'] ?? []),
);
diff --git a/rag/Config/ServerConfig.php b/rag/Config/ServerConfig.php
new file mode 100644
index 00000000..1958a02f
--- /dev/null
+++ b/rag/Config/ServerConfig.php
@@ -0,0 +1,35 @@
+getConfig();
+ $allCollections = $config->getCollectionNames();
+
+ if ($this->collection !== null) {
+ if (!$config->hasCollection($this->collection)) {
+ throw new \InvalidArgumentException(
+ \sprintf(
+ 'Collection "%s" not found. Available: %s',
+ $this->collection,
+ \implode(', ', $allCollections),
+ ),
+ );
+ }
+
+ return [$this->collection];
+ }
+
+ return $allCollections;
+ }
+
+ /**
+ * Output section header for collection operations.
+ */
+ protected function outputCollectionHeader(OutputInterface $output, string $collectionName, string $operation): void
+ {
+ $output->writeln('');
+ $output->writeln(\sprintf('━━━ %s: %s ━━━', $operation, $collectionName));
+ }
+}
diff --git a/rag/Console/RagClearCommand.php b/rag/Console/RagClearCommand.php
index ae36c9eb..7ad0e2cd 100644
--- a/rag/Console/RagClearCommand.php
+++ b/rag/Console/RagClearCommand.php
@@ -9,11 +9,11 @@
use Butschster\ContextGenerator\Console\BaseCommand;
use Butschster\ContextGenerator\DirectoriesInterface;
use Butschster\ContextGenerator\Rag\RagRegistryInterface;
+use Butschster\ContextGenerator\Rag\Store\StoreRegistryInterface;
use Spiral\Console\Attribute\Option;
use Spiral\Core\Container;
use Spiral\Core\Scope;
use Symfony\AI\Store\ManagedStoreInterface;
-use Symfony\AI\Store\StoreInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
@@ -23,21 +23,15 @@
)]
final class RagClearCommand extends BaseCommand
{
+ use CollectionAwareTrait;
+
#[Option(shortcut: 'f', description: 'Force clear without confirmation')]
protected bool $force = false;
- #[Option(
- name: 'config-file',
- shortcut: 'c',
- description: 'Path to configuration file',
- )]
+ #[Option(name: 'config-file', shortcut: 'c', description: 'Path to configuration file')]
protected ?string $configPath = null;
- #[Option(
- name: 'env',
- shortcut: 'e',
- description: 'Path to .env file (e.g., .env.local)',
- )]
+ #[Option(name: 'env', shortcut: 'e', description: 'Path to .env file (e.g., .env.local)')]
protected ?string $envFile = null;
public function __invoke(
@@ -49,23 +43,16 @@ public function __invoke(
->withEnvFile($this->envFile);
return $container->runScope(
- bindings: new Scope(
- bindings: [
- DirectoriesInterface::class => $dirs,
- ],
- ),
+ bindings: new Scope(bindings: [DirectoriesInterface::class => $dirs]),
scope: function (
ConfigurationProvider $configProvider,
RagRegistryInterface $registry,
- Container $container,
+ StoreRegistryInterface $storeRegistry,
): int {
- // Load configuration to trigger RagParserPlugin
try {
- if ($this->configPath !== null) {
- $configLoader = $configProvider->fromPath($this->configPath);
- } else {
- $configLoader = $configProvider->fromDefaultLocation();
- }
+ $configLoader = $this->configPath !== null
+ ? $configProvider->fromPath($this->configPath)
+ : $configProvider->fromDefaultLocation();
$configLoader->load();
} catch (ConfigLoaderException $e) {
$this->output->error(\sprintf('Failed to load configuration: %s', $e->getMessage()));
@@ -77,43 +64,64 @@ public function __invoke(
return Command::FAILURE;
}
- $config = $registry->getConfig();
+ try {
+ $collections = $this->getTargetCollections($registry);
+ } catch (\InvalidArgumentException $e) {
+ $this->output->error($e->getMessage());
+ return Command::FAILURE;
+ }
$this->output->title('RAG Clear');
- $this->output->writeln(\sprintf('Collection: %s', $config->store->collection));
+ $this->output->writeln(\sprintf('Collections: %s', \implode(', ', $collections)));
$this->output->writeln('');
- // Get store after config is loaded
- $store = $container->get(StoreInterface::class);
+ $cleared = 0;
+ $skipped = 0;
- if (!$store instanceof ManagedStoreInterface) {
- $this->output->error('Store does not support clearing operations.');
- return Command::FAILURE;
- }
+ foreach ($collections as $collectionName) {
+ $this->outputCollectionHeader($this->output, $collectionName, 'Clearing');
- if (!$this->force) {
- $confirm = $this->output->confirm(
- 'This will delete all entries in the knowledge base. Continue?',
- false,
- );
+ $collectionConfig = $registry->getConfig()->getCollection($collectionName);
+ $this->output->writeln(\sprintf(' Target: %s', $collectionConfig->collection));
- if (!$confirm) {
- $this->output->writeln('Operation cancelled.');
- return Command::SUCCESS;
+ $store = $storeRegistry->getStore($collectionName);
+
+ if (!$store instanceof ManagedStoreInterface) {
+ $this->output->writeln(' Store does not support clearing');
+ $skipped++;
+ continue;
}
- }
- $this->output->write('Clearing knowledge base... ');
+ if (!$this->force) {
+ $confirm = $this->output->confirm(
+ \sprintf(' Clear all entries in "%s"?', $collectionName),
+ false,
+ );
+ if (!$confirm) {
+ $this->output->writeln(' Skipped');
+ $skipped++;
+ continue;
+ }
+ }
- try {
- $store->drop();
- $store->setup();
- $this->output->writeln('Done');
- $this->output->success('Knowledge base cleared successfully.');
- } catch (\Throwable $e) {
- $this->output->writeln('Failed');
- $this->output->error(\sprintf('Failed to clear knowledge base: %s', $e->getMessage()));
- return Command::FAILURE;
+ $this->output->write(' Clearing... ');
+ try {
+ $store->drop();
+ $store->setup();
+ $this->output->writeln('Done');
+ $cleared++;
+ } catch (\Throwable $e) {
+ $this->output->writeln('Failed');
+ $this->output->error(\sprintf(' Error: %s', $e->getMessage()));
+ }
+ }
+
+ $this->output->writeln('');
+ if ($cleared > 0) {
+ $this->output->success(\sprintf('Cleared %d collection(s)', $cleared));
+ }
+ if ($skipped > 0) {
+ $this->output->writeln(\sprintf('Skipped %d collection(s)', $skipped));
}
return Command::SUCCESS;
diff --git a/rag/Console/RagIndexCommand.php b/rag/Console/RagIndexCommand.php
index 337705b1..63809a6a 100644
--- a/rag/Console/RagIndexCommand.php
+++ b/rag/Console/RagIndexCommand.php
@@ -11,7 +11,7 @@
use Butschster\ContextGenerator\Rag\Document\DocumentType;
use Butschster\ContextGenerator\Rag\Loader\FileSystemLoader;
use Butschster\ContextGenerator\Rag\RagRegistryInterface;
-use Butschster\ContextGenerator\Rag\Service\IndexerService;
+use Butschster\ContextGenerator\Rag\Service\ServiceFactory;
use Spiral\Console\Attribute\Argument;
use Spiral\Console\Attribute\Option;
use Spiral\Core\Container;
@@ -26,6 +26,8 @@
)]
final class RagIndexCommand extends BaseCommand
{
+ use CollectionAwareTrait;
+
#[Argument(description: 'Directory path to index (relative to project root)')]
protected string $path;
@@ -41,18 +43,10 @@ final class RagIndexCommand extends BaseCommand
#[Option(description: 'Dry run - show what would be indexed without indexing')]
protected bool $dryRun = false;
- #[Option(
- name: 'config-file',
- shortcut: 'c',
- description: 'Path to configuration file',
- )]
+ #[Option(name: 'config-file', shortcut: 'c', description: 'Path to configuration file')]
protected ?string $configPath = null;
- #[Option(
- name: 'env',
- shortcut: 'e',
- description: 'Path to .env file (e.g., .env.local)',
- )]
+ #[Option(name: 'env', shortcut: 'e', description: 'Path to .env file (e.g., .env.local)')]
protected ?string $envFile = null;
public function __invoke(
@@ -64,25 +58,18 @@ public function __invoke(
->withEnvFile($this->envFile);
return $container->runScope(
- bindings: new Scope(
- bindings: [
- DirectoriesInterface::class => $dirs,
- ],
- ),
+ bindings: new Scope(bindings: [DirectoriesInterface::class => $dirs]),
scope: function (
ConfigurationProvider $configProvider,
RagRegistryInterface $registry,
FileSystemLoader $loader,
DirectoriesInterface $dirs,
- Container $container,
+ ServiceFactory $serviceFactory,
): int {
- // Load configuration to trigger RagParserPlugin
try {
- if ($this->configPath !== null) {
- $configLoader = $configProvider->fromPath($this->configPath);
- } else {
- $configLoader = $configProvider->fromDefaultLocation();
- }
+ $configLoader = $this->configPath !== null
+ ? $configProvider->fromPath($this->configPath)
+ : $configProvider->fromDefaultLocation();
$configLoader->load();
} catch (ConfigLoaderException $e) {
$this->output->error(\sprintf('Failed to load configuration: %s', $e->getMessage()));
@@ -95,21 +82,26 @@ public function __invoke(
}
$fullPath = $dirs->getRootPath()->join($this->path)->toString();
-
if (!\is_dir($fullPath)) {
$this->output->error(\sprintf('Directory not found: %s', $this->path));
return Command::FAILURE;
}
+ try {
+ $collections = $this->getTargetCollections($registry);
+ } catch (\InvalidArgumentException $e) {
+ $this->output->error($e->getMessage());
+ return Command::FAILURE;
+ }
+
$this->output->title('RAG Index');
- $this->output->writeln(\sprintf('Path: %s', $this->path));
- $this->output->writeln(\sprintf('Pattern: %s', $this->pattern));
- $this->output->writeln(\sprintf('Type: %s', $this->type));
- $this->output->writeln(\sprintf('Recursive: %s', $this->recursive ? 'Yes' : 'No'));
- $this->output->writeln('');
+ $this->output->writeln(\sprintf('Path: %s', $this->path));
+ $this->output->writeln(\sprintf('Pattern: %s', $this->pattern));
+ $this->output->writeln(\sprintf('Type: %s', $this->type));
+ $this->output->writeln(\sprintf('Recursive: %s', $this->recursive ? 'Yes' : 'No'));
+ $this->output->writeln(\sprintf('Collections: %s', \implode(', ', $collections)));
$total = $loader->count($fullPath, $this->pattern, $this->recursive);
-
if ($total === 0) {
$this->output->warning('No files found matching the pattern.');
return Command::SUCCESS;
@@ -120,44 +112,56 @@ public function __invoke(
$docType = DocumentType::tryFrom($this->type) ?? DocumentType::General;
if ($this->dryRun) {
- $this->output->writeln('');
$this->output->note('Dry run - no changes made');
-
foreach ($loader->load($fullPath, $this->pattern, $this->recursive, $docType) as $doc) {
$this->output->writeln(\sprintf(' • %s', $doc->getMetadata()['source_path'] ?? 'unknown'));
}
-
return Command::SUCCESS;
}
- // Get IndexerService after config is loaded (so factories have resolved variables)
- $indexer = $container->get(IndexerService::class);
+ $overallChunks = 0;
+ $overallTime = 0.0;
- $this->output->writeln('');
+ foreach ($collections as $collectionName) {
+ $this->outputCollectionHeader($this->output, $collectionName, 'Indexing');
- $progressBar = new ProgressBar($this->output, $total);
- $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%');
- $progressBar->start();
+ $collectionConfig = $registry->getConfig()->getCollection($collectionName);
+ $this->output->writeln(\sprintf(' Target: %s', $collectionConfig->collection));
- $totalChunks = 0;
- $totalTime = 0.0;
+ $indexer = $serviceFactory->getIndexer($collectionName);
+ $progressBar = new ProgressBar($this->output, $total);
+ $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%');
+ $progressBar->start();
- foreach ($loader->load($fullPath, $this->pattern, $this->recursive, $docType) as $doc) {
- $result = $indexer->indexBatch([$doc]);
- $totalChunks += $result->chunksCreated;
- $totalTime += $result->processingTimeMs;
- $progressBar->advance();
- }
+ $totalChunks = 0;
+ $totalTime = 0.0;
+
+ foreach ($loader->load($fullPath, $this->pattern, $this->recursive, $docType) as $doc) {
+ $result = $indexer->indexBatch([$doc]);
+ $totalChunks += $result->chunksCreated;
+ $totalTime += $result->processingTimeMs;
+ $progressBar->advance();
+ }
- $progressBar->finish();
+ $progressBar->finish();
+ $this->output->writeln('');
+ $this->output->writeln(\sprintf(
+ ' ✓ Indexed %d chunks in %.2fs',
+ $totalChunks,
+ $totalTime / 1000,
+ ));
+
+ $overallChunks += $totalChunks;
+ $overallTime += $totalTime;
+ }
- $this->output->writeln('');
$this->output->writeln('');
$this->output->success(\sprintf(
- 'Indexed %d files into %d chunks (%.2fs)',
+ 'Total: %d files → %d chunks across %d collection(s) (%.2fs)',
$total,
- $totalChunks,
- $totalTime / 1000,
+ $overallChunks,
+ \count($collections),
+ $overallTime / 1000,
));
return Command::SUCCESS;
diff --git a/rag/Console/RagInitCommand.php b/rag/Console/RagInitCommand.php
new file mode 100644
index 00000000..5264f7ca
--- /dev/null
+++ b/rag/Console/RagInitCommand.php
@@ -0,0 +1,276 @@
+determineRootPath($this->configPath)
+ ->withEnvFile($this->envFile);
+
+ return $container->runScope(
+ bindings: new Scope(bindings: [DirectoriesInterface::class => $dirs]),
+ scope: function (
+ ConfigurationProvider $configProvider,
+ RagRegistryInterface $registry,
+ VariableResolver $variableResolver,
+ StoreRegistryInterface $storeRegistry,
+ ): int {
+ try {
+ $configLoader = $this->configPath !== null
+ ? $configProvider->fromPath($this->configPath)
+ : $configProvider->fromDefaultLocation();
+ $configLoader->load();
+ } catch (ConfigLoaderException $e) {
+ $this->output->error(\sprintf('Failed to load configuration: %s', $e->getMessage()));
+ return Command::FAILURE;
+ }
+
+ if (!$registry->isEnabled()) {
+ $this->output->error('RAG is not enabled in configuration. Add "rag.enabled: true" to context.yaml');
+ return Command::FAILURE;
+ }
+
+ try {
+ $collections = $this->getTargetCollections($registry);
+ } catch (\InvalidArgumentException $e) {
+ $this->output->error($e->getMessage());
+ return Command::FAILURE;
+ }
+
+ $config = $registry->getConfig();
+
+ $this->output->title('RAG Collection Initialization');
+ $this->output->writeln(\sprintf('Collections: %s', \implode(', ', $collections)));
+ $this->output->writeln('');
+
+ $initialized = 0;
+ $skipped = 0;
+ $failed = 0;
+
+ foreach ($collections as $collectionName) {
+ $this->outputCollectionHeader($this->output, $collectionName, 'Initializing');
+
+ $collectionConfig = $config->getCollection($collectionName);
+ $serverConfig = $config->getServer($collectionConfig->server);
+
+ $endpointUrl = $variableResolver->resolve($serverConfig->endpointUrl);
+ $apiKey = $variableResolver->resolve($serverConfig->apiKey);
+ $qdrantCollection = $variableResolver->resolve($collectionConfig->collection);
+
+ $dimension = $collectionConfig->getEffectiveEmbeddingsDimension($serverConfig);
+ $distance = $collectionConfig->getEffectiveEmbeddingsDistance($serverConfig);
+
+ $this->output->writeln(\sprintf(' Server: %s', $collectionConfig->server));
+ $this->output->writeln(\sprintf(' Driver: %s', $serverConfig->driver));
+ $this->output->writeln(\sprintf(' Endpoint: %s', $endpointUrl));
+ $this->output->writeln(\sprintf(' Collection: %s', $qdrantCollection));
+ $this->output->writeln(\sprintf(' Dimensions: %d', $dimension));
+ $this->output->writeln(\sprintf(' Distance: %s', $distance));
+
+ if ($serverConfig->driver !== 'qdrant') {
+ $result = $this->initializeGenericStore($storeRegistry, $collectionName);
+ } else {
+ $result = $this->initializeQdrantStore(
+ storeRegistry: $storeRegistry,
+ collectionName: $collectionName,
+ endpointUrl: $endpointUrl,
+ apiKey: $apiKey,
+ qdrantCollection: $qdrantCollection,
+ );
+ }
+
+ match ($result) {
+ 'initialized' => $initialized++,
+ 'skipped' => $skipped++,
+ 'failed' => $failed++,
+ };
+ }
+
+ $this->output->writeln('');
+ if ($initialized > 0) {
+ $this->output->success(\sprintf('Initialized %d collection(s)', $initialized));
+ }
+ if ($skipped > 0) {
+ $this->output->writeln(\sprintf('Skipped %d collection(s)', $skipped));
+ }
+ if ($failed > 0) {
+ $this->output->writeln(\sprintf('Failed %d collection(s)', $failed));
+ }
+
+ return $failed > 0 ? Command::FAILURE : Command::SUCCESS;
+ },
+ );
+ }
+
+ private function initializeQdrantStore(
+ StoreRegistryInterface $storeRegistry,
+ string $collectionName,
+ string $endpointUrl,
+ string $apiKey,
+ string $qdrantCollection,
+ ): string {
+ $httpClient = HttpClient::create();
+ $headers = $apiKey !== '' ? ['api-key' => $apiKey] : [];
+
+ // Check connection
+ $this->output->write(' Checking connection... ');
+ try {
+ $response = $httpClient->request('GET', \rtrim($endpointUrl, '/') . '/collections', [
+ 'headers' => $headers,
+ 'timeout' => 10,
+ ]);
+
+ if ($response->getStatusCode() !== 200) {
+ $this->output->writeln('Failed');
+ $this->output->error(\sprintf(' Qdrant returned status %d', $response->getStatusCode()));
+ return 'failed';
+ }
+ $this->output->writeln('OK');
+ } catch (\Throwable $e) {
+ $this->output->writeln('Failed');
+ $this->output->error(\sprintf(' Cannot connect: %s', $e->getMessage()));
+ return 'failed';
+ }
+
+ // Check if collection exists
+ $this->output->write(\sprintf(' Checking collection "%s"... ', $qdrantCollection));
+ $collectionExists = false;
+
+ try {
+ $response = $httpClient->request(
+ 'GET',
+ \rtrim($endpointUrl, '/') . '/collections/' . $qdrantCollection,
+ ['headers' => $headers],
+ );
+
+ if ($response->getStatusCode() === 200) {
+ $collectionExists = true;
+ $this->output->writeln('Exists');
+ } else {
+ $this->output->writeln('Not found');
+ }
+ } catch (\Throwable $e) {
+ if (\str_contains($e->getMessage(), '404')) {
+ $this->output->writeln('Not found');
+ } else {
+ $this->output->writeln('Error');
+ $this->output->error(\sprintf(' Failed to check: %s', $e->getMessage()));
+ return 'failed';
+ }
+ }
+
+ if ($collectionExists) {
+ if (!$this->force) {
+ $this->output->writeln(' Collection already exists. Use --force to recreate.');
+ return 'skipped';
+ }
+
+ $confirm = $this->output->confirm(
+ ' Collection exists. DROP and recreate?',
+ false,
+ );
+
+ if (!$confirm) {
+ return 'skipped';
+ }
+
+ return $this->recreateStore($storeRegistry, $collectionName);
+ }
+
+ return $this->createStore($storeRegistry, $collectionName);
+ }
+
+ private function initializeGenericStore(StoreRegistryInterface $storeRegistry, string $collectionName): string
+ {
+ return $this->createStore($storeRegistry, $collectionName);
+ }
+
+ private function createStore(StoreRegistryInterface $storeRegistry, string $collectionName): string
+ {
+ $store = $storeRegistry->getStore($collectionName);
+
+ if (!$store instanceof ManagedStoreInterface) {
+ $this->output->writeln(' Store does not support initialization');
+ return 'skipped';
+ }
+
+ $this->output->write(' Creating collection... ');
+ try {
+ $store->setup();
+ $this->output->writeln('Done');
+ return 'initialized';
+ } catch (\Throwable $e) {
+ $this->output->writeln('Failed');
+ $this->output->error(\sprintf(' Error: %s', $e->getMessage()));
+ return 'failed';
+ }
+ }
+
+ private function recreateStore(StoreRegistryInterface $storeRegistry, string $collectionName): string
+ {
+ $store = $storeRegistry->getStore($collectionName);
+
+ if (!$store instanceof ManagedStoreInterface) {
+ $this->output->writeln(' Store does not support recreation');
+ return 'skipped';
+ }
+
+ $this->output->write(' Dropping existing... ');
+ try {
+ $store->drop();
+ $this->output->writeln('Done');
+ } catch (\Throwable $e) {
+ $this->output->writeln('Failed');
+ $this->output->error(\sprintf(' Error: %s', $e->getMessage()));
+ return 'failed';
+ }
+
+ $this->output->write(' Creating new... ');
+ try {
+ $store->setup();
+ $this->output->writeln('Done');
+ return 'initialized';
+ } catch (\Throwable $e) {
+ $this->output->writeln('Failed');
+ $this->output->error(\sprintf(' Error: %s', $e->getMessage()));
+ return 'failed';
+ }
+ }
+}
diff --git a/rag/Console/RagReindexCommand.php b/rag/Console/RagReindexCommand.php
index 61b4f8e3..9328b939 100644
--- a/rag/Console/RagReindexCommand.php
+++ b/rag/Console/RagReindexCommand.php
@@ -11,13 +11,13 @@
use Butschster\ContextGenerator\Rag\Document\DocumentType;
use Butschster\ContextGenerator\Rag\Loader\FileSystemLoader;
use Butschster\ContextGenerator\Rag\RagRegistryInterface;
-use Butschster\ContextGenerator\Rag\Service\IndexerService;
+use Butschster\ContextGenerator\Rag\Service\ServiceFactory;
+use Butschster\ContextGenerator\Rag\Store\StoreRegistryInterface;
use Spiral\Console\Attribute\Argument;
use Spiral\Console\Attribute\Option;
use Spiral\Core\Container;
use Spiral\Core\Scope;
use Symfony\AI\Store\ManagedStoreInterface;
-use Symfony\AI\Store\StoreInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
@@ -28,6 +28,8 @@
)]
final class RagReindexCommand extends BaseCommand
{
+ use CollectionAwareTrait;
+
#[Argument(description: 'Directory path to index (relative to project root)')]
protected string $path;
@@ -43,18 +45,10 @@ final class RagReindexCommand extends BaseCommand
#[Option(shortcut: 'f', description: 'Force reindex without confirmation')]
protected bool $force = false;
- #[Option(
- name: 'config-file',
- shortcut: 'c',
- description: 'Path to configuration file',
- )]
+ #[Option(name: 'config-file', shortcut: 'c', description: 'Path to configuration file')]
protected ?string $configPath = null;
- #[Option(
- name: 'env',
- shortcut: 'e',
- description: 'Path to .env file (e.g., .env.local)',
- )]
+ #[Option(name: 'env', shortcut: 'e', description: 'Path to .env file (e.g., .env.local)')]
protected ?string $envFile = null;
public function __invoke(
@@ -66,25 +60,19 @@ public function __invoke(
->withEnvFile($this->envFile);
return $container->runScope(
- bindings: new Scope(
- bindings: [
- DirectoriesInterface::class => $dirs,
- ],
- ),
+ bindings: new Scope(bindings: [DirectoriesInterface::class => $dirs]),
scope: function (
ConfigurationProvider $configProvider,
RagRegistryInterface $registry,
FileSystemLoader $loader,
DirectoriesInterface $dirs,
- Container $container,
+ ServiceFactory $serviceFactory,
+ StoreRegistryInterface $storeRegistry,
): int {
- // Load configuration to trigger RagParserPlugin
try {
- if ($this->configPath !== null) {
- $configLoader = $configProvider->fromPath($this->configPath);
- } else {
- $configLoader = $configProvider->fromDefaultLocation();
- }
+ $configLoader = $this->configPath !== null
+ ? $configProvider->fromPath($this->configPath)
+ : $configProvider->fromDefaultLocation();
$configLoader->load();
} catch (ConfigLoaderException $e) {
$this->output->error(\sprintf('Failed to load configuration: %s', $e->getMessage()));
@@ -97,24 +85,26 @@ public function __invoke(
}
$fullPath = $dirs->getRootPath()->join($this->path)->toString();
-
if (!\is_dir($fullPath)) {
$this->output->error(\sprintf('Directory not found: %s', $this->path));
return Command::FAILURE;
}
- $config = $registry->getConfig();
+ try {
+ $collections = $this->getTargetCollections($registry);
+ } catch (\InvalidArgumentException $e) {
+ $this->output->error($e->getMessage());
+ return Command::FAILURE;
+ }
$this->output->title('RAG Reindex');
- $this->output->writeln(\sprintf('Collection: %s', $config->store->collection));
- $this->output->writeln(\sprintf('Path: %s', $this->path));
- $this->output->writeln(\sprintf('Pattern: %s', $this->pattern));
- $this->output->writeln(\sprintf('Type: %s', $this->type));
- $this->output->writeln(\sprintf('Recursive: %s', $this->recursive ? 'Yes' : 'No'));
- $this->output->writeln('');
+ $this->output->writeln(\sprintf('Path: %s', $this->path));
+ $this->output->writeln(\sprintf('Pattern: %s', $this->pattern));
+ $this->output->writeln(\sprintf('Type: %s', $this->type));
+ $this->output->writeln(\sprintf('Recursive: %s', $this->recursive ? 'Yes' : 'No'));
+ $this->output->writeln(\sprintf('Collections: %s', \implode(', ', $collections)));
$total = $loader->count($fullPath, $this->pattern, $this->recursive);
-
if ($total === 0) {
$this->output->warning('No files found matching the pattern.');
return Command::SUCCESS;
@@ -124,7 +114,7 @@ public function __invoke(
if (!$this->force) {
$confirm = $this->output->confirm(
- 'This will clear the knowledge base and reindex. Continue?',
+ 'This will clear and reindex the knowledge base. Continue?',
false,
);
@@ -134,54 +124,66 @@ public function __invoke(
}
}
- // Get services after config is loaded (so factories have resolved variables)
- $store = $container->get(StoreInterface::class);
- $indexer = $container->get(IndexerService::class);
-
- // Step 1: Clear
- if ($store instanceof ManagedStoreInterface) {
- $this->output->writeln('');
- $this->output->write('Clearing existing entries... ');
- try {
- $store->drop();
- $store->setup();
- $this->output->writeln('Done');
- } catch (\Throwable $e) {
- $this->output->writeln('Failed');
- $this->output->error(\sprintf('Failed to clear: %s', $e->getMessage()));
- return Command::FAILURE;
+ $docType = DocumentType::tryFrom($this->type) ?? DocumentType::General;
+ $overallChunks = 0;
+ $overallTime = 0.0;
+
+ foreach ($collections as $collectionName) {
+ $this->outputCollectionHeader($this->output, $collectionName, 'Reindexing');
+
+ $collectionConfig = $registry->getConfig()->getCollection($collectionName);
+ $this->output->writeln(\sprintf(' Target: %s', $collectionConfig->collection));
+
+ // Step 1: Clear
+ $store = $storeRegistry->getStore($collectionName);
+ if ($store instanceof ManagedStoreInterface) {
+ $this->output->write(' Clearing existing entries... ');
+ try {
+ $store->drop();
+ $store->setup();
+ $this->output->writeln('Done');
+ } catch (\Throwable $e) {
+ $this->output->writeln('Failed');
+ $this->output->error(\sprintf(' Error: %s', $e->getMessage()));
+ continue;
+ }
}
- }
- // Step 2: Index
- $this->output->writeln('Indexing files...');
- $this->output->writeln('');
-
- $docType = DocumentType::tryFrom($this->type) ?? DocumentType::General;
+ // Step 2: Index
+ $indexer = $serviceFactory->getIndexer($collectionName);
+ $progressBar = new ProgressBar($this->output, $total);
+ $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%');
+ $progressBar->start();
- $progressBar = new ProgressBar($this->output, $total);
- $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%');
- $progressBar->start();
+ $totalChunks = 0;
+ $totalTime = 0.0;
- $totalChunks = 0;
- $totalTime = 0.0;
+ foreach ($loader->load($fullPath, $this->pattern, $this->recursive, $docType) as $doc) {
+ $result = $indexer->indexBatch([$doc]);
+ $totalChunks += $result->chunksCreated;
+ $totalTime += $result->processingTimeMs;
+ $progressBar->advance();
+ }
- foreach ($loader->load($fullPath, $this->pattern, $this->recursive, $docType) as $doc) {
- $result = $indexer->indexBatch([$doc]);
- $totalChunks += $result->chunksCreated;
- $totalTime += $result->processingTimeMs;
- $progressBar->advance();
+ $progressBar->finish();
+ $this->output->writeln('');
+ $this->output->writeln(\sprintf(
+ ' ✓ Reindexed %d chunks in %.2fs',
+ $totalChunks,
+ $totalTime / 1000,
+ ));
+
+ $overallChunks += $totalChunks;
+ $overallTime += $totalTime;
}
- $progressBar->finish();
-
- $this->output->writeln('');
$this->output->writeln('');
$this->output->success(\sprintf(
- 'Reindexed %d files into %d chunks (%.2fs)',
+ 'Total: %d files → %d chunks across %d collection(s) (%.2fs)',
$total,
- $totalChunks,
- $totalTime / 1000,
+ $overallChunks,
+ \count($collections),
+ $overallTime / 1000,
));
return Command::SUCCESS;
diff --git a/rag/Console/RagStatusCommand.php b/rag/Console/RagStatusCommand.php
index a7b4f2be..cc1b82da 100644
--- a/rag/Console/RagStatusCommand.php
+++ b/rag/Console/RagStatusCommand.php
@@ -8,6 +8,7 @@
use Butschster\ContextGenerator\Config\Exception\ConfigLoaderException;
use Butschster\ContextGenerator\Console\BaseCommand;
use Butschster\ContextGenerator\DirectoriesInterface;
+use Butschster\ContextGenerator\Rag\Config\RagConfig;
use Butschster\ContextGenerator\Rag\RagRegistryInterface;
use Spiral\Console\Attribute\Option;
use Spiral\Core\Container;
@@ -21,21 +22,15 @@
)]
final class RagStatusCommand extends BaseCommand
{
+ use CollectionAwareTrait;
+
#[Option(name: 'json', description: 'Output as JSON')]
protected bool $asJson = false;
- #[Option(
- name: 'config-file',
- shortcut: 'c',
- description: 'Path to configuration file',
- )]
+ #[Option(name: 'config-file', shortcut: 'c', description: 'Path to configuration file')]
protected ?string $configPath = null;
- #[Option(
- name: 'env',
- shortcut: 'e',
- description: 'Path to .env file (e.g., .env.local)',
- )]
+ #[Option(name: 'env', shortcut: 'e', description: 'Path to .env file (e.g., .env.local)')]
protected ?string $envFile = null;
public function __invoke(
@@ -47,22 +42,15 @@ public function __invoke(
->withEnvFile($this->envFile);
return $container->runScope(
- bindings: new Scope(
- bindings: [
- DirectoriesInterface::class => $dirs,
- ],
- ),
+ bindings: new Scope(bindings: [DirectoriesInterface::class => $dirs]),
scope: function (
ConfigurationProvider $configProvider,
RagRegistryInterface $registry,
): int {
- // Load configuration to trigger RagParserPlugin
try {
- if ($this->configPath !== null) {
- $loader = $configProvider->fromPath($this->configPath);
- } else {
- $loader = $configProvider->fromDefaultLocation();
- }
+ $loader = $this->configPath !== null
+ ? $configProvider->fromPath($this->configPath)
+ : $configProvider->fromDefaultLocation();
$loader->load();
} catch (ConfigLoaderException $e) {
$this->output->error(\sprintf('Failed to load configuration: %s', $e->getMessage()));
@@ -72,50 +60,121 @@ public function __invoke(
$config = $registry->getConfig();
if ($this->asJson) {
- $this->output->writeln(\json_encode([
- 'enabled' => $config->enabled,
- 'store' => [
- 'driver' => $config->store->driver,
- 'endpoint_url' => $config->store->endpointUrl,
- 'collection' => $config->store->collection,
- 'embeddings_dimension' => $config->store->embeddingsDimension,
- ],
- 'vectorizer' => [
- 'platform' => $config->vectorizer->platform,
- 'model' => $config->vectorizer->model,
- ],
- 'transformer' => [
- 'chunk_size' => $config->transformer->chunkSize,
- 'overlap' => $config->transformer->overlap,
- ],
- ], \JSON_PRETTY_PRINT));
-
- return Command::SUCCESS;
+ return $this->outputJson($config);
}
- $this->output->title('RAG Knowledge Base Status');
+ return $this->outputFormatted($config, $registry);
+ },
+ );
+ }
- $this->output->writeln(\sprintf('Enabled: %s', $config->enabled ? 'Yes' : 'No'));
- $this->output->writeln('');
+ private function outputJson(RagConfig $config): int
+ {
+ $data = [
+ 'enabled' => $config->enabled,
+ 'format' => $config->isLegacyFormat() ? 'legacy' : 'new',
+ 'vectorizer' => [
+ 'platform' => $config->vectorizer->platform,
+ 'model' => $config->vectorizer->model,
+ ],
+ 'transformer' => [
+ 'chunk_size' => $config->transformer->chunkSize,
+ 'overlap' => $config->transformer->overlap,
+ ],
+ 'servers' => [],
+ 'collections' => [],
+ ];
+
+ foreach ($config->servers as $name => $server) {
+ $data['servers'][$name] = [
+ 'driver' => $server->driver,
+ 'endpoint_url' => $server->endpointUrl,
+ 'embeddings_dimension' => $server->embeddingsDimension,
+ 'embeddings_distance' => $server->embeddingsDistance,
+ ];
+ }
+
+ foreach ($config->collections as $name => $collection) {
+ $data['collections'][$name] = [
+ 'server' => $collection->server,
+ 'collection' => $collection->collection,
+ 'description' => $collection->description,
+ 'embeddings_dimension' => $collection->embeddingsDimension,
+ 'embeddings_distance' => $collection->embeddingsDistance,
+ 'transformer' => $collection->transformer !== null ? [
+ 'chunk_size' => $collection->transformer->chunkSize,
+ 'overlap' => $collection->transformer->overlap,
+ ] : null,
+ ];
+ }
+
+ $this->output->writeln(\json_encode($data, \JSON_PRETTY_PRINT));
+
+ return Command::SUCCESS;
+ }
- $this->output->section('Store Configuration');
- $this->output->writeln(\sprintf(' Driver: %s', $config->store->driver));
- $this->output->writeln(\sprintf(' Endpoint: %s', $config->store->endpointUrl));
- $this->output->writeln(\sprintf(' Collection: %s', $config->store->collection));
- $this->output->writeln(\sprintf(' Dimensions: %d', $config->store->embeddingsDimension));
+ private function outputFormatted(RagConfig $config, RagRegistryInterface $registry): int
+ {
+ $this->output->title('RAG Knowledge Base Status');
+
+ $this->output->writeln(\sprintf('Enabled: %s', $config->enabled ? 'Yes' : 'No'));
+ $this->output->writeln(\sprintf('Format: %s', $config->isLegacyFormat() ? 'Legacy' : 'Multi-collection'));
+ $this->output->writeln('');
+
+ // Global Vectorizer
+ $this->output->section('Vectorizer Configuration');
+ $this->output->writeln(\sprintf(' Platform: %s', $config->vectorizer->platform));
+ $this->output->writeln(\sprintf(' Model: %s', $config->vectorizer->model));
+ $this->output->writeln('');
+
+ // Default Transformer
+ $this->output->section('Default Transformer');
+ $this->output->writeln(\sprintf(' Chunk Size: %d', $config->transformer->chunkSize));
+ $this->output->writeln(\sprintf(' Overlap: %d', $config->transformer->overlap));
+ $this->output->writeln('');
+
+ // Servers
+ if (!empty($config->servers)) {
+ $this->output->section('Servers');
+ foreach ($config->servers as $name => $server) {
+ $this->output->writeln(\sprintf(' %s:', $name));
+ $this->output->writeln(\sprintf(' Driver: %s', $server->driver));
+ $this->output->writeln(\sprintf(' Endpoint: %s', $server->endpointUrl));
+ $this->output->writeln(\sprintf(' Dimensions: %d', $server->embeddingsDimension));
+ $this->output->writeln(\sprintf(' Distance: %s', $server->embeddingsDistance));
$this->output->writeln('');
-
- $this->output->section('Vectorizer Configuration');
- $this->output->writeln(\sprintf(' Platform: %s', $config->vectorizer->platform));
- $this->output->writeln(\sprintf(' Model: %s', $config->vectorizer->model));
+ }
+ }
+
+ // Collections
+ try {
+ $collections = $this->getTargetCollections($registry);
+ } catch (\InvalidArgumentException $e) {
+ $this->output->error($e->getMessage());
+ return Command::FAILURE;
+ }
+
+ if (!empty($collections)) {
+ $this->output->section('Collections');
+ foreach ($collections as $name) {
+ $coll = $config->getCollection($name);
+ $this->output->writeln(\sprintf(' %s:', $name));
+ $this->output->writeln(\sprintf(' Server: %s', $coll->server));
+ $this->output->writeln(\sprintf(' Collection: %s', $coll->collection));
+ if ($coll->description !== null) {
+ $this->output->writeln(\sprintf(' Description: %s', $coll->description));
+ }
+ if ($coll->embeddingsDimension !== null) {
+ $this->output->writeln(\sprintf(' Dimensions: %d (override)', $coll->embeddingsDimension));
+ }
+ if ($coll->transformer !== null) {
+ $this->output->writeln(\sprintf(' Chunk Size: %d (override)', $coll->transformer->chunkSize));
+ $this->output->writeln(\sprintf(' Overlap: %d (override)', $coll->transformer->overlap));
+ }
$this->output->writeln('');
+ }
+ }
- $this->output->section('Transformer Configuration');
- $this->output->writeln(\sprintf(' Chunk Size: %d', $config->transformer->chunkSize));
- $this->output->writeln(\sprintf(' Overlap: %d', $config->transformer->overlap));
-
- return Command::SUCCESS;
- },
- );
+ return Command::SUCCESS;
}
}
diff --git a/rag/MCP/Tools/RagSearch/RagSearchHandler.php b/rag/MCP/Tools/RagSearch/RagSearchHandler.php
index a1fb35f0..85ce414b 100644
--- a/rag/MCP/Tools/RagSearch/RagSearchHandler.php
+++ b/rag/MCP/Tools/RagSearch/RagSearchHandler.php
@@ -6,12 +6,13 @@
use Butschster\ContextGenerator\Rag\Document\DocumentType;
use Butschster\ContextGenerator\Rag\MCP\Tools\RagSearch\Dto\RagSearchRequest;
-use Butschster\ContextGenerator\Rag\Service\RetrieverService;
+use Butschster\ContextGenerator\Rag\Service\ServiceFactory;
final readonly class RagSearchHandler
{
public function __construct(
- private RetrieverService $retriever,
+ private ServiceFactory $serviceFactory,
+ private string $collectionName = 'default',
) {}
public function handle(RagSearchRequest $request): string
@@ -21,8 +22,9 @@ public function handle(RagSearchRequest $request): string
}
$type = $request->type !== null ? DocumentType::tryFrom($request->type) : null;
+ $retriever = $this->serviceFactory->getRetriever($this->collectionName);
- $results = $this->retriever->search(
+ $results = $retriever->search(
query: $request->query,
limit: $request->limit,
type: $type,
@@ -30,10 +32,10 @@ public function handle(RagSearchRequest $request): string
);
if ($results === []) {
- return \sprintf('No results found for "%s"', $request->query);
+ return \sprintf('No results found for "%s" in [%s]', $request->query, $this->collectionName);
}
- $output = [\sprintf('Found %d results for "%s"', \count($results), $request->query), ''];
+ $output = [\sprintf('Found %d results for "%s" in [%s]', \count($results), $request->query, $this->collectionName), ''];
foreach ($results as $i => $item) {
$output[] = \sprintf('--- Result %d ---', $i + 1);
@@ -43,4 +45,12 @@ public function handle(RagSearchRequest $request): string
return \implode("\n", $output);
}
+
+ /**
+ * Create handler for specific collection.
+ */
+ public function withCollection(string $collectionName): self
+ {
+ return new self($this->serviceFactory, $collectionName);
+ }
}
diff --git a/rag/MCP/Tools/RagStore/RagStoreHandler.php b/rag/MCP/Tools/RagStore/RagStoreHandler.php
index b9a76947..b5180e5e 100644
--- a/rag/MCP/Tools/RagStore/RagStoreHandler.php
+++ b/rag/MCP/Tools/RagStore/RagStoreHandler.php
@@ -6,12 +6,13 @@
use Butschster\ContextGenerator\Rag\Document\DocumentType;
use Butschster\ContextGenerator\Rag\MCP\Tools\RagStore\Dto\RagStoreRequest;
-use Butschster\ContextGenerator\Rag\Service\IndexerService;
+use Butschster\ContextGenerator\Rag\Service\ServiceFactory;
final readonly class RagStoreHandler
{
public function __construct(
- private IndexerService $indexer,
+ private ServiceFactory $serviceFactory,
+ private string $collectionName = 'default',
) {}
public function handle(RagStoreRequest $request): string
@@ -21,8 +22,9 @@ public function handle(RagStoreRequest $request): string
}
$type = DocumentType::tryFrom($request->type) ?? DocumentType::General;
+ $indexer = $this->serviceFactory->getIndexer($this->collectionName);
- $result = $this->indexer->index(
+ $result = $indexer->index(
content: $request->content,
type: $type,
sourcePath: $request->sourcePath,
@@ -30,10 +32,19 @@ public function handle(RagStoreRequest $request): string
);
return \sprintf(
- "Stored in knowledge base.\nType: %s | Chunks: %d | Time: %.2fms",
+ "Stored in knowledge base [%s].\nType: %s | Chunks: %d | Time: %.2fms",
+ $this->collectionName,
$type->value,
$result->chunksCreated,
$result->processingTimeMs,
);
}
+
+ /**
+ * Create handler for specific collection.
+ */
+ public function withCollection(string $collectionName): self
+ {
+ return new self($this->serviceFactory, $collectionName);
+ }
}
diff --git a/rag/RagBootloader.php b/rag/RagBootloader.php
index b5f2f791..9be5dd9d 100644
--- a/rag/RagBootloader.php
+++ b/rag/RagBootloader.php
@@ -6,16 +6,26 @@
use Butschster\ContextGenerator\Application\Bootloader\ConsoleBootloader;
use Butschster\ContextGenerator\Config\ConfigLoaderBootloader;
+use Butschster\ContextGenerator\McpServer\Tool\RagToolExecutorInterface;
use Butschster\ContextGenerator\Rag\Config\RagConfig;
use Butschster\ContextGenerator\Rag\Console\RagClearCommand;
use Butschster\ContextGenerator\Rag\Console\RagIndexCommand;
+use Butschster\ContextGenerator\Rag\Console\RagInitCommand;
use Butschster\ContextGenerator\Rag\Console\RagReindexCommand;
use Butschster\ContextGenerator\Rag\Console\RagStatusCommand;
use Butschster\ContextGenerator\Rag\Document\MetadataFactory;
use Butschster\ContextGenerator\Rag\Loader\FileSystemLoader;
use Butschster\ContextGenerator\Rag\Service\IndexerService;
use Butschster\ContextGenerator\Rag\Service\RetrieverService;
+use Butschster\ContextGenerator\Rag\Service\ServiceFactory;
use Butschster\ContextGenerator\Rag\Store\StoreFactory;
+use Butschster\ContextGenerator\Rag\Store\StoreRegistry;
+use Butschster\ContextGenerator\Rag\Store\StoreRegistryInterface;
+use Butschster\ContextGenerator\Rag\Tool\RagToolExecutor;
+use Butschster\ContextGenerator\Rag\Tool\RagToolFactory;
+use Butschster\ContextGenerator\Rag\Tool\RagToolParserPlugin;
+use Butschster\ContextGenerator\Rag\Tool\RagToolRegistry;
+use Butschster\ContextGenerator\Rag\Tool\RagToolRegistryInterface;
use Butschster\ContextGenerator\Rag\Vectorizer\VectorizerFactory;
use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Core\Attribute\Singleton;
@@ -37,15 +47,27 @@ public function defineDependencies(): array
public function defineSingletons(): array
{
return [
- // Registry
+ // Registries
RagRegistryInterface::class => RagRegistry::class,
+ RagToolRegistryInterface::class => RagToolRegistry::class,
+ RagToolRegistry::class => RagToolRegistry::class,
// Factories
StoreFactory::class => StoreFactory::class,
VectorizerFactory::class => VectorizerFactory::class,
MetadataFactory::class => MetadataFactory::class,
+ // Store registry for multi-collection support
+ StoreRegistryInterface::class => static fn(
+ RagRegistryInterface $ragRegistry,
+ StoreFactory $factory,
+ ): StoreRegistryInterface => new StoreRegistry(
+ ragRegistry: $ragRegistry,
+ factory: $factory,
+ ),
+
// Symfony AI Store components (created from registry config)
+ // Uses first/default collection for backward compatibility
StoreInterface::class => static fn(
StoreFactory $factory,
RagRegistryInterface $registry,
@@ -59,9 +81,34 @@ public function defineSingletons(): array
// Provide RagConfig from registry for convenience
RagConfig::class => static fn(RagRegistryInterface $registry): RagConfig => $registry->getConfig(),
- // Services
- IndexerService::class => IndexerService::class,
- RetrieverService::class => RetrieverService::class,
+ // Service factory for multi-collection support
+ ServiceFactory::class => ServiceFactory::class,
+
+ // RAG tool factory for dynamic tools
+ RagToolFactory::class => RagToolFactory::class,
+
+ // RAG tool executor for MCP tool handler
+ RagToolExecutorInterface::class => RagToolExecutor::class,
+
+ // Legacy IndexerService binding - uses default/first collection
+ IndexerService::class => static function (ServiceFactory $factory): IndexerService {
+ $collectionNames = $factory->getCollectionNames();
+ if (empty($collectionNames)) {
+ throw new \RuntimeException('No RAG collections configured');
+ }
+
+ return $factory->getIndexer($collectionNames[0]);
+ },
+
+ // Legacy RetrieverService binding - uses default/first collection
+ RetrieverService::class => static function (ServiceFactory $factory): RetrieverService {
+ $collectionNames = $factory->getCollectionNames();
+ if (empty($collectionNames)) {
+ throw new \RuntimeException('No RAG collections configured');
+ }
+
+ return $factory->getRetriever($collectionNames[0]);
+ },
// Loader
FileSystemLoader::class => FileSystemLoader::class,
@@ -71,13 +118,16 @@ public function defineSingletons(): array
public function boot(
ConfigLoaderBootloader $configLoader,
RagParserPlugin $ragParser,
+ RagToolParserPlugin $ragToolParser,
ConsoleBootloader $console,
): void {
- // Register parser plugin (like ExcludeBootloader)
+ // Register parser plugins
$configLoader->registerParserPlugin($ragParser);
+ $configLoader->registerParserPlugin($ragToolParser);
// Register CLI commands
$console->addCommand(RagStatusCommand::class);
+ $console->addCommand(RagInitCommand::class);
$console->addCommand(RagIndexCommand::class);
$console->addCommand(RagClearCommand::class);
$console->addCommand(RagReindexCommand::class);
diff --git a/rag/RagParserPlugin.php b/rag/RagParserPlugin.php
index b1739d8c..ad3c56cc 100644
--- a/rag/RagParserPlugin.php
+++ b/rag/RagParserPlugin.php
@@ -42,12 +42,7 @@ public function parse(array $config, string $rootPath): ?RegistryInterface
$ragConfig = RagConfig::fromArray($config['rag']);
$this->registry->setConfig($ragConfig);
- $this->logger?->info('Parsed RAG configuration', [
- 'enabled' => $ragConfig->enabled,
- 'store_driver' => $ragConfig->store->driver,
- 'vectorizer_platform' => $ragConfig->vectorizer->platform,
- 'vectorizer_model' => $ragConfig->vectorizer->model,
- ]);
+ $this->logConfiguration($ragConfig);
return $this->registry;
}
@@ -56,4 +51,25 @@ public function updateConfig(array $config, string $rootPath): array
{
return $config;
}
+
+ private function logConfiguration(RagConfig $ragConfig): void
+ {
+ if ($ragConfig->isLegacyFormat()) {
+ $this->logger?->info('Parsed RAG configuration (legacy format)', [
+ 'enabled' => $ragConfig->enabled,
+ 'store_driver' => $ragConfig->store?->driver,
+ 'collection' => $ragConfig->store?->collection,
+ 'vectorizer_platform' => $ragConfig->vectorizer->platform,
+ 'vectorizer_model' => $ragConfig->vectorizer->model,
+ ]);
+ } else {
+ $this->logger?->info('Parsed RAG configuration (new format)', [
+ 'enabled' => $ragConfig->enabled,
+ 'servers' => $ragConfig->getServerNames(),
+ 'collections' => $ragConfig->getCollectionNames(),
+ 'vectorizer_platform' => $ragConfig->vectorizer->platform,
+ 'vectorizer_model' => $ragConfig->vectorizer->model,
+ ]);
+ }
+ }
}
diff --git a/rag/RagRegistry.php b/rag/RagRegistry.php
index bab85c83..f4fd417e 100644
--- a/rag/RagRegistry.php
+++ b/rag/RagRegistry.php
@@ -60,14 +60,8 @@ public function getIterator(): \Traversable
public function jsonSerialize(): array
{
- return [
+ $result = [
'enabled' => $this->config->enabled,
- 'store' => [
- 'driver' => $this->config->store->driver,
- 'endpoint_url' => $this->config->store->endpointUrl,
- 'collection' => $this->config->store->collection,
- 'embeddings_dimension' => $this->config->store->embeddingsDimension,
- ],
'vectorizer' => [
'platform' => $this->config->vectorizer->platform,
'model' => $this->config->vectorizer->model,
@@ -77,5 +71,40 @@ public function jsonSerialize(): array
'overlap' => $this->config->transformer->overlap,
],
];
+
+ // Include legacy store info if present
+ if ($this->config->store !== null) {
+ $result['store'] = [
+ 'driver' => $this->config->store->driver,
+ 'endpoint_url' => $this->config->store->endpointUrl,
+ 'collection' => $this->config->store->collection,
+ 'embeddings_dimension' => $this->config->store->embeddingsDimension,
+ ];
+ }
+
+ // Include new format info
+ if (!empty($this->config->servers)) {
+ $result['servers'] = \array_map(
+ static fn($server) => [
+ 'driver' => $server->driver,
+ 'endpoint_url' => $server->endpointUrl,
+ 'embeddings_dimension' => $server->embeddingsDimension,
+ ],
+ $this->config->servers,
+ );
+ }
+
+ if (!empty($this->config->collections)) {
+ $result['collections'] = \array_map(
+ static fn($collection) => [
+ 'server' => $collection->server,
+ 'collection' => $collection->collection,
+ 'description' => $collection->description,
+ ],
+ $this->config->collections,
+ );
+ }
+
+ return $result;
}
}
diff --git a/rag/Service/IndexerService.php b/rag/Service/IndexerService.php
index 7c84bf20..2eddb089 100644
--- a/rag/Service/IndexerService.php
+++ b/rag/Service/IndexerService.php
@@ -4,7 +4,7 @@
namespace Butschster\ContextGenerator\Rag\Service;
-use Butschster\ContextGenerator\Rag\Config\RagConfig;
+use Butschster\ContextGenerator\Rag\Config\TransformerConfig;
use Butschster\ContextGenerator\Rag\Document\DocumentType;
use Butschster\ContextGenerator\Rag\Document\MetadataFactory;
use Symfony\AI\Store\Document\TextDocument;
@@ -21,11 +21,11 @@ public function __construct(
private StoreInterface $store,
private VectorizerInterface $vectorizer,
private MetadataFactory $metadataFactory,
- RagConfig $config,
+ TransformerConfig $transformerConfig,
) {
$this->transformer = new TextSplitTransformer(
- chunkSize: $config->transformer->chunkSize,
- overlap: $config->transformer->overlap,
+ chunkSize: $transformerConfig->chunkSize,
+ overlap: $transformerConfig->overlap,
);
}
diff --git a/rag/Service/ServiceFactory.php b/rag/Service/ServiceFactory.php
new file mode 100644
index 00000000..bd0a80bf
--- /dev/null
+++ b/rag/Service/ServiceFactory.php
@@ -0,0 +1,126 @@
+ */
+ private array $indexers = [];
+
+ /** @var array */
+ private array $retrievers = [];
+
+ public function __construct(
+ private readonly RagRegistryInterface $ragRegistry,
+ private readonly StoreRegistryInterface $storeRegistry,
+ private readonly VectorizerFactory $vectorizerFactory,
+ private readonly MetadataFactory $metadataFactory,
+ #[LoggerPrefix(prefix: 'service-factory')]
+ private readonly ?LoggerInterface $logger = null,
+ ) {}
+
+ /**
+ * Get IndexerService for a specific collection.
+ */
+ public function getIndexer(string $collectionName): IndexerService
+ {
+ if (!isset($this->indexers[$collectionName])) {
+ $this->indexers[$collectionName] = $this->createIndexer($collectionName);
+ }
+
+ return $this->indexers[$collectionName];
+ }
+
+ /**
+ * Get RetrieverService for a specific collection.
+ */
+ public function getRetriever(string $collectionName): RetrieverService
+ {
+ if (!isset($this->retrievers[$collectionName])) {
+ $this->retrievers[$collectionName] = $this->createRetriever($collectionName);
+ }
+
+ return $this->retrievers[$collectionName];
+ }
+
+ /**
+ * Get all collection names.
+ *
+ * @return string[]
+ */
+ public function getCollectionNames(): array
+ {
+ return $this->storeRegistry->getCollectionNames();
+ }
+
+ /**
+ * Check if a collection exists.
+ */
+ public function hasCollection(string $collectionName): bool
+ {
+ return $this->storeRegistry->hasCollection($collectionName);
+ }
+
+ private function getConfig(): RagConfig
+ {
+ return $this->ragRegistry->getConfig();
+ }
+
+ private function createIndexer(string $collectionName): IndexerService
+ {
+ $collectionConfig = $this->storeRegistry->getCollectionConfig($collectionName);
+ $transformerConfig = $collectionConfig->getTransformer($this->getConfig()->transformer);
+
+ $this->logger?->debug('Creating IndexerService', [
+ 'collection' => $collectionName,
+ 'chunk_size' => $transformerConfig->chunkSize,
+ 'overlap' => $transformerConfig->overlap,
+ ]);
+
+ return new IndexerService(
+ store: $this->storeRegistry->getStore($collectionName),
+ vectorizer: $this->getVectorizer(),
+ metadataFactory: $this->metadataFactory,
+ transformerConfig: $transformerConfig,
+ );
+ }
+
+ private function createRetriever(string $collectionName): RetrieverService
+ {
+ $this->logger?->debug('Creating RetrieverService', [
+ 'collection' => $collectionName,
+ ]);
+
+ return new RetrieverService(
+ store: $this->storeRegistry->getStore($collectionName),
+ vectorizer: $this->getVectorizer(),
+ );
+ }
+
+ private function getVectorizer(): VectorizerInterface
+ {
+ if ($this->vectorizer === null) {
+ $this->vectorizer = $this->vectorizerFactory->create($this->getConfig());
+ }
+
+ return $this->vectorizer;
+ }
+}
diff --git a/rag/Store/StoreFactory.php b/rag/Store/StoreFactory.php
index 64e9236c..b28df13a 100644
--- a/rag/Store/StoreFactory.php
+++ b/rag/Store/StoreFactory.php
@@ -5,7 +5,10 @@
namespace Butschster\ContextGenerator\Rag\Store;
use Butschster\ContextGenerator\Lib\Variable\VariableResolver;
+use Butschster\ContextGenerator\Rag\Config\CollectionConfig;
use Butschster\ContextGenerator\Rag\Config\RagConfig;
+use Butschster\ContextGenerator\Rag\Config\ServerConfig;
+use Butschster\ContextGenerator\Rag\Config\StoreConfig;
use Symfony\AI\Store\Bridge\Qdrant\Store as QdrantStore;
use Symfony\AI\Store\InMemory\Store as InMemoryStore;
use Symfony\AI\Store\StoreInterface;
@@ -17,20 +20,80 @@ public function __construct(
private VariableResolver $variableResolver,
) {}
+ /**
+ * Create store for a specific collection using new config structure.
+ */
+ public function createForCollection(
+ ServerConfig $serverConfig,
+ CollectionConfig $collectionConfig,
+ ): StoreInterface {
+ return match ($serverConfig->driver) {
+ 'qdrant' => $this->createQdrantStore($serverConfig, $collectionConfig),
+ 'memory', 'in_memory' => new InMemoryStore(),
+ default => throw new \InvalidArgumentException(
+ \sprintf('Unknown RAG store driver: %s', $serverConfig->driver),
+ ),
+ };
+ }
+
+ /**
+ * Create store from RagConfig (supports both legacy and new format).
+ */
public function create(RagConfig $config): StoreInterface
{
- return match ($config->store->driver) {
+ // New format: use first collection
+ if (!empty($config->collections)) {
+ $collectionName = \array_key_first($config->collections);
+ $collectionConfig = $config->getCollection($collectionName);
+ $serverConfig = $config->getServer($collectionConfig->server);
+
+ return $this->createForCollection($serverConfig, $collectionConfig);
+ }
+
+ // Legacy format: use store config directly
+ if ($config->store !== null) {
+ return $this->createFromLegacyStoreConfig($config->store);
+ }
+
+ throw new \InvalidArgumentException('No collections or legacy store config found');
+ }
+
+ private function createQdrantStore(
+ ServerConfig $serverConfig,
+ CollectionConfig $collectionConfig,
+ ): QdrantStore {
+ $endpointUrl = $this->variableResolver->resolve($serverConfig->endpointUrl);
+ $apiKey = $this->variableResolver->resolve($serverConfig->apiKey);
+ $collectionName = $this->variableResolver->resolve($collectionConfig->collection);
+
+ // Use collection-level overrides or server defaults
+ $dimension = $collectionConfig->getEffectiveEmbeddingsDimension($serverConfig);
+ $distance = $collectionConfig->getEffectiveEmbeddingsDistance($serverConfig);
+
+ return new QdrantStore(
+ httpClient: HttpClient::create(),
+ endpointUrl: $endpointUrl,
+ apiKey: $apiKey,
+ collectionName: $collectionName,
+ embeddingsDimension: $dimension,
+ embeddingsDistance: $distance,
+ );
+ }
+
+ private function createFromLegacyStoreConfig(StoreConfig $config): StoreInterface
+ {
+ return match ($config->driver) {
'qdrant' => new QdrantStore(
httpClient: HttpClient::create(),
- endpointUrl: $this->variableResolver->resolve($config->store->endpointUrl),
- apiKey: $this->variableResolver->resolve($config->store->apiKey),
- collectionName: $this->variableResolver->resolve($config->store->collection),
- embeddingsDimension: $config->store->embeddingsDimension,
- embeddingsDistance: $config->store->embeddingsDistance,
+ endpointUrl: $this->variableResolver->resolve($config->endpointUrl),
+ apiKey: $this->variableResolver->resolve($config->apiKey),
+ collectionName: $this->variableResolver->resolve($config->collection),
+ embeddingsDimension: $config->embeddingsDimension,
+ embeddingsDistance: $config->embeddingsDistance,
),
'memory', 'in_memory' => new InMemoryStore(),
default => throw new \InvalidArgumentException(
- \sprintf('Unknown RAG store driver: %s', $config->store->driver),
+ \sprintf('Unknown RAG store driver: %s', $config->driver),
),
};
}
diff --git a/rag/Store/StoreRegistry.php b/rag/Store/StoreRegistry.php
new file mode 100644
index 00000000..33dfe7d0
--- /dev/null
+++ b/rag/Store/StoreRegistry.php
@@ -0,0 +1,80 @@
+ */
+ private array $stores = [];
+
+ public function __construct(
+ private readonly RagRegistryInterface $ragRegistry,
+ private readonly StoreFactory $factory,
+ #[LoggerPrefix(prefix: 'store-registry')]
+ private readonly ?LoggerInterface $logger = null,
+ ) {}
+
+ public function getStore(string $collectionName): StoreInterface
+ {
+ if (!$this->hasCollection($collectionName)) {
+ throw new \InvalidArgumentException(
+ \sprintf('Collection "%s" not found in RAG configuration', $collectionName),
+ );
+ }
+
+ if (!isset($this->stores[$collectionName])) {
+ $this->stores[$collectionName] = $this->createStore($collectionName);
+ }
+
+ return $this->stores[$collectionName];
+ }
+
+ public function hasCollection(string $collectionName): bool
+ {
+ return $this->getConfig()->hasCollection($collectionName);
+ }
+
+ public function getCollectionConfig(string $collectionName): CollectionConfig
+ {
+ return $this->getConfig()->getCollection($collectionName);
+ }
+
+ public function getCollectionNames(): array
+ {
+ return $this->getConfig()->getCollectionNames();
+ }
+
+ private function getConfig(): RagConfig
+ {
+ return $this->ragRegistry->getConfig();
+ }
+
+ private function createStore(string $collectionName): StoreInterface
+ {
+ $config = $this->getConfig();
+ $collectionConfig = $config->getCollection($collectionName);
+ $serverConfig = $config->getServer($collectionConfig->server);
+
+ $this->logger?->debug('Creating store for collection', [
+ 'collection' => $collectionName,
+ 'server' => $collectionConfig->server,
+ 'driver' => $serverConfig->driver,
+ ]);
+
+ return $this->factory->createForCollection($serverConfig, $collectionConfig);
+ }
+}
diff --git a/rag/Store/StoreRegistryInterface.php b/rag/Store/StoreRegistryInterface.php
new file mode 100644
index 00000000..ade485fa
--- /dev/null
+++ b/rag/Store/StoreRegistryInterface.php
@@ -0,0 +1,41 @@
+config->getSearchToolId();
+ }
+
+ public function getToolName(): string
+ {
+ return $this->config->getName();
+ }
+
+ public function getToolDescription(): string
+ {
+ return $this->config->description;
+ }
+
+ public function getToolTitle(): string
+ {
+ return $this->config->getName() ?? \ucfirst(\str_replace(['-', '_'], ' ', $this->config->id));
+ }
+
+ /**
+ * Get JSON schema for this tool's input.
+ */
+ public function getInputSchema(): array
+ {
+ return [
+ 'type' => 'object',
+ 'properties' => [
+ 'query' => [
+ 'type' => 'string',
+ 'description' => 'Search query in natural language',
+ ],
+ 'type' => [
+ 'type' => 'string',
+ 'description' => 'Filter by type: architecture, api, testing, convention, tutorial, reference, general',
+ ],
+ 'sourcePath' => [
+ 'type' => 'string',
+ 'description' => 'Filter by source path (exact or prefix match)',
+ ],
+ 'limit' => [
+ 'type' => 'integer',
+ 'description' => 'Maximum number of results to return',
+ 'default' => 10,
+ 'minimum' => 1,
+ 'maximum' => 50,
+ ],
+ ],
+ 'required' => ['query'],
+ ];
+ }
+
+ public function __invoke(RagSearchRequest $request): CallToolResult
+ {
+ $this->logger->info('Dynamic RAG Search', [
+ 'tool' => $this->config->id,
+ 'collection' => $this->config->collection,
+ 'query' => $request->query,
+ ]);
+
+ try {
+ $handler = new RagSearchHandler($this->serviceFactory, $this->config->collection);
+
+ return ToolResult::text($handler->handle($request));
+ } catch (\Throwable $e) {
+ $this->logger->error('Dynamic RAG Search error', [
+ 'tool' => $this->config->id,
+ 'error' => $e->getMessage(),
+ ]);
+
+ return ToolResult::error($e->getMessage());
+ }
+ }
+}
diff --git a/rag/Tool/DynamicRagStoreAction.php b/rag/Tool/DynamicRagStoreAction.php
new file mode 100644
index 00000000..f0f2fa41
--- /dev/null
+++ b/rag/Tool/DynamicRagStoreAction.php
@@ -0,0 +1,99 @@
+config->getSearchToolId();
+ }
+
+ public function getToolName(): string
+ {
+ return $this->config->getName();
+ }
+
+ public function getToolDescription(): string
+ {
+ return $this->config->description . ' (store operation)';
+ }
+
+ public function getToolTitle(): string
+ {
+ return $this->config->getName() ?? \ucfirst(\str_replace(['-', '_'], ' ', $this->config->id)) . ' Store';
+ }
+
+ /**
+ * Get JSON schema for this tool's input.
+ */
+ public function getInputSchema(): array
+ {
+ return [
+ 'type' => 'object',
+ 'properties' => [
+ 'content' => [
+ 'type' => 'string',
+ 'description' => 'Content to store in the knowledge base',
+ ],
+ 'type' => [
+ 'type' => 'string',
+ 'description' => 'Type: architecture, api, testing, convention, tutorial, reference, general',
+ 'default' => 'general',
+ ],
+ 'sourcePath' => [
+ 'type' => 'string',
+ 'description' => 'Source path (e.g., "src/Auth/Service.php")',
+ ],
+ 'tags' => [
+ 'type' => 'string',
+ 'description' => 'Tags (comma-separated)',
+ ],
+ ],
+ 'required' => ['content'],
+ ];
+ }
+
+ public function __invoke(RagStoreRequest $request): CallToolResult
+ {
+ $this->logger->info('Dynamic RAG Store', [
+ 'tool' => $this->config->id,
+ 'collection' => $this->config->collection,
+ 'type' => $request->type,
+ ]);
+
+ try {
+ $handler = new RagStoreHandler($this->serviceFactory, $this->config->collection);
+
+ return ToolResult::text($handler->handle($request));
+ } catch (\Throwable $e) {
+ $this->logger->error('Dynamic RAG Store error', [
+ 'tool' => $this->config->id,
+ 'error' => $e->getMessage(),
+ ]);
+
+ return ToolResult::error($e->getMessage());
+ }
+ }
+}
diff --git a/rag/Tool/RagToolConfig.php b/rag/Tool/RagToolConfig.php
new file mode 100644
index 00000000..10c4b379
--- /dev/null
+++ b/rag/Tool/RagToolConfig.php
@@ -0,0 +1,113 @@
+validateOperations($operations);
+ }
+
+ public static function fromArray(array $data): self
+ {
+ if (empty($data['id']) || !\is_string($data['id'])) {
+ throw new \InvalidArgumentException('RAG tool must have a non-empty id');
+ }
+
+ if (empty($data['description']) || !\is_string($data['description'])) {
+ throw new \InvalidArgumentException('RAG tool must have a non-empty description');
+ }
+
+ if (empty($data['collection']) || !\is_string($data['collection'])) {
+ throw new \InvalidArgumentException('RAG tool must specify a collection');
+ }
+
+ $operations = $data['operations'] ?? [self::OPERATION_SEARCH, self::OPERATION_STORE];
+ if (!\is_array($operations)) {
+ throw new \InvalidArgumentException('RAG tool operations must be an array');
+ }
+
+ return new self(
+ id: $data['id'],
+ name: isset($data['name']) && \is_string($data['name']) ? $data['name'] : null,
+ description: $data['description'],
+ collection: $data['collection'],
+ operations: \array_values($operations),
+ );
+ }
+
+ /**
+ * Get the tool name (uses name if provided, otherwise id).
+ */
+ public function getName(): string
+ {
+ return $this->name;
+ }
+
+ public function hasSearch(): bool
+ {
+ return \in_array(self::OPERATION_SEARCH, $this->operations, true);
+ }
+
+ public function hasStore(): bool
+ {
+ return \in_array(self::OPERATION_STORE, $this->operations, true);
+ }
+
+ /**
+ * Get the tool ID for search operation.
+ */
+ public function getSearchToolId(): string
+ {
+ return $this->id;
+ }
+
+ /**
+ * Get the tool ID for store operation.
+ */
+ public function getStoreToolId(): string
+ {
+ return $this->id . '-store';
+ }
+
+ private function validateOperations(array $operations): void
+ {
+ $valid = [self::OPERATION_SEARCH, self::OPERATION_STORE];
+
+ foreach ($operations as $op) {
+ if (!\in_array($op, $valid, true)) {
+ throw new \InvalidArgumentException(
+ \sprintf('Invalid RAG operation "%s". Valid: %s', $op, \implode(', ', $valid)),
+ );
+ }
+ }
+
+ if (empty($operations)) {
+ throw new \InvalidArgumentException('RAG tool must have at least one operation');
+ }
+ }
+}
diff --git a/rag/Tool/RagToolExecutor.php b/rag/Tool/RagToolExecutor.php
new file mode 100644
index 00000000..55197a9a
--- /dev/null
+++ b/rag/Tool/RagToolExecutor.php
@@ -0,0 +1,104 @@
+logger->info('Executing RAG search', [
+ 'collection' => $collection,
+ 'query' => $arguments['query'] ?? null,
+ ]);
+
+ try {
+ $request = new RagSearchRequest(
+ query: $arguments['query'] ?? '',
+ type: $arguments['type'] ?? null,
+ sourcePath: $arguments['sourcePath'] ?? null,
+ limit: isset($arguments['limit']) ? (int) $arguments['limit'] : 10,
+ );
+
+ $handler = new RagSearchHandler($this->serviceFactory, $collection);
+ $output = $handler->handle($request);
+
+ return [
+ 'output' => $output,
+ 'success' => true,
+ ];
+ } catch (\Throwable $e) {
+ $this->logger->error('RAG search failed', [
+ 'collection' => $collection,
+ 'error' => $e->getMessage(),
+ ]);
+
+ return [
+ 'output' => 'Search failed: ' . $e->getMessage(),
+ 'success' => false,
+ ];
+ }
+ }
+
+ public function store(string $collection, array $arguments): array
+ {
+ $this->logger->info('Executing RAG store', [
+ 'collection' => $collection,
+ 'type' => $arguments['type'] ?? 'general',
+ ]);
+
+ try {
+ $request = new RagStoreRequest(
+ content: $arguments['content'] ?? '',
+ type: $arguments['type'] ?? 'general',
+ sourcePath: $arguments['sourcePath'] ?? null,
+ tags: $arguments['tags'] ?? null,
+ );
+
+ $handler = new RagStoreHandler($this->serviceFactory, $collection);
+ $output = $handler->handle($request);
+
+ return [
+ 'output' => $output,
+ 'success' => true,
+ ];
+ } catch (\Throwable $e) {
+ $this->logger->error('RAG store failed', [
+ 'collection' => $collection,
+ 'error' => $e->getMessage(),
+ ]);
+
+ return [
+ 'output' => 'Store failed: ' . $e->getMessage(),
+ 'success' => false,
+ ];
+ }
+ }
+
+ public function hasCollection(string $collection): bool
+ {
+ return $this->ragRegistry->getConfig()->hasCollection($collection);
+ }
+}
diff --git a/rag/Tool/RagToolFactory.php b/rag/Tool/RagToolFactory.php
new file mode 100644
index 00000000..e7a235eb
--- /dev/null
+++ b/rag/Tool/RagToolFactory.php
@@ -0,0 +1,87 @@
+toolRegistry->all() as $toolConfig) {
+ // Validate collection exists
+ if (!$this->ragRegistry->getConfig()->hasCollection($toolConfig->collection)) {
+ $this->logger->warning('RAG tool references non-existent collection', [
+ 'tool' => $toolConfig->id,
+ 'collection' => $toolConfig->collection,
+ ]);
+ continue;
+ }
+
+ if ($toolConfig->hasSearch()) {
+ $searchActions[] = $this->createSearchAction($toolConfig);
+ $this->logger->debug('Created search action', ['tool' => $toolConfig->id]);
+ }
+
+ if ($toolConfig->hasStore()) {
+ $storeActions[] = $this->createStoreAction($toolConfig);
+ $this->logger->debug('Created store action', ['tool' => $toolConfig->id]);
+ }
+ }
+
+ return [
+ 'search' => $searchActions,
+ 'store' => $storeActions,
+ ];
+ }
+
+ /**
+ * Check if there are any dynamic RAG tools to register.
+ */
+ public function hasTools(): bool
+ {
+ return $this->toolRegistry->hasTools();
+ }
+
+ public function createSearchAction(RagToolConfig $config): DynamicRagSearchAction
+ {
+ return new DynamicRagSearchAction(
+ config: $config,
+ serviceFactory: $this->serviceFactory,
+ logger: $this->logger,
+ );
+ }
+
+ public function createStoreAction(RagToolConfig $config): DynamicRagStoreAction
+ {
+ return new DynamicRagStoreAction(
+ config: $config,
+ serviceFactory: $this->serviceFactory,
+ logger: $this->logger,
+ );
+ }
+}
diff --git a/rag/Tool/RagToolParserPlugin.php b/rag/Tool/RagToolParserPlugin.php
new file mode 100644
index 00000000..5556771d
--- /dev/null
+++ b/rag/Tool/RagToolParserPlugin.php
@@ -0,0 +1,105 @@
+ragRegistry->isEnabled();
+ }
+
+ public function parse(array $config, string $rootPath): ?RegistryInterface
+ {
+ if (!$this->supports($config)) {
+ return null;
+ }
+
+ $ragConfig = $this->ragRegistry->getConfig();
+
+ foreach ($config['tools'] as $index => $toolConfig) {
+ // Only process RAG-type tools
+ if (($toolConfig['type'] ?? '') !== 'rag') {
+ continue;
+ }
+
+ try {
+ $ragTool = RagToolConfig::fromArray($toolConfig);
+
+ // Validate collection exists
+ if (!$ragConfig->hasCollection($ragTool->collection)) {
+ throw new \InvalidArgumentException(
+ \sprintf(
+ 'RAG tool "%s" references non-existent collection "%s". Available: %s',
+ $ragTool->id,
+ $ragTool->collection,
+ \implode(', ', $ragConfig->getCollectionNames()),
+ ),
+ );
+ }
+
+ $this->toolRegistry->register($ragTool);
+
+ $this->logger?->debug('RAG tool registered', [
+ 'id' => $ragTool->id,
+ 'collection' => $ragTool->collection,
+ 'operations' => $ragTool->operations,
+ ]);
+ } catch (\Throwable $e) {
+ $this->logger?->warning('Failed to parse RAG tool', [
+ 'index' => $index,
+ 'id' => $toolConfig['id'] ?? 'unknown',
+ 'error' => $e->getMessage(),
+ ]);
+
+ throw new \InvalidArgumentException(
+ \sprintf('Failed to parse RAG tool at index %d: %s', $index, $e->getMessage()),
+ previous: $e,
+ );
+ }
+ }
+
+ $this->logger?->info('Parsed RAG tools', [
+ 'count' => \count($this->toolRegistry->all()),
+ ]);
+
+ // Return null as we don't own a registry - RagToolRegistry is managed separately
+ return null;
+ }
+
+ public function updateConfig(array $config, string $rootPath): array
+ {
+ return $config;
+ }
+}
diff --git a/rag/Tool/RagToolRegistry.php b/rag/Tool/RagToolRegistry.php
new file mode 100644
index 00000000..82ed1b54
--- /dev/null
+++ b/rag/Tool/RagToolRegistry.php
@@ -0,0 +1,46 @@
+ */
+ private array $tools = [];
+
+ public function register(RagToolConfig $tool): void
+ {
+ $this->tools[$tool->id] = $tool;
+ }
+
+ public function all(): array
+ {
+ return \array_values($this->tools);
+ }
+
+ public function hasTools(): bool
+ {
+ return !empty($this->tools);
+ }
+
+ public function get(string $id): RagToolConfig
+ {
+ if (!$this->has($id)) {
+ throw new \InvalidArgumentException(\sprintf('RAG tool "%s" not found', $id));
+ }
+
+ return $this->tools[$id];
+ }
+
+ public function has(string $id): bool
+ {
+ return isset($this->tools[$id]);
+ }
+}
diff --git a/rag/Tool/RagToolRegistryInterface.php b/rag/Tool/RagToolRegistryInterface.php
new file mode 100644
index 00000000..83925886
--- /dev/null
+++ b/rag/Tool/RagToolRegistryInterface.php
@@ -0,0 +1,40 @@
+getPath();
- if (\strlen($description) > self::MAX_LINE_WIDTH - 40) {
+ /** @psalm-suppress RedundantCast */
+ if (\strlen((string) $description) > self::MAX_LINE_WIDTH - 40) {
$halfLength = (self::MAX_LINE_WIDTH - 40) / 2;
- $description = \substr($description, 0, $halfLength) . '...' . \substr($description, -$halfLength);
+ /** @psalm-suppress RedundantCast */
+ $description = \substr((string) $description, 0, $halfLength) . '...' . \substr((string) $description, -$halfLength);
}
// Calculate padding to align the document descriptions
diff --git a/src/McpServer/ActionsBootloader.php b/src/McpServer/ActionsBootloader.php
index 66de9e24..f563ea6c 100644
--- a/src/McpServer/ActionsBootloader.php
+++ b/src/McpServer/ActionsBootloader.php
@@ -44,13 +44,13 @@
use Butschster\ContextGenerator\McpServer\Projects\Console\ProjectRemoveCommand;
use Butschster\ContextGenerator\McpServer\Prompt\Console\ListPromptsCommand;
use Butschster\ContextGenerator\McpServer\Prompt\Console\ShowPromptCommand;
+use Butschster\ContextGenerator\McpServer\Registry\McpItemsRegistry;
use Butschster\ContextGenerator\McpServer\Tool\Console\ToolListCommand;
use Butschster\ContextGenerator\McpServer\Tool\Console\ToolRunCommand;
use Butschster\ContextGenerator\McpServer\Tool\Console\ToolSchemaCommand;
-use Butschster\ContextGenerator\Rag\MCP\Tools\RagManage\RagManageAction;
-use Butschster\ContextGenerator\Rag\MCP\Tools\RagSearch\RagSearchAction;
-use Butschster\ContextGenerator\Rag\MCP\Tools\RagStore\RagStoreAction;
use Butschster\ContextGenerator\Rag\RagRegistryInterface;
+use Butschster\ContextGenerator\Rag\Tool\RagToolFactory;
+use Butschster\ContextGenerator\Rag\Tool\RagToolRegistryInterface;
use Butschster\ContextGenerator\Research\MCP\Tools\CreateEntryToolAction;
use Butschster\ContextGenerator\Research\MCP\Tools\CreateResearchToolAction;
use Butschster\ContextGenerator\Research\MCP\Tools\GetResearchToolAction;
@@ -60,6 +60,8 @@
use Butschster\ContextGenerator\Research\MCP\Tools\ReadEntryToolAction;
use Butschster\ContextGenerator\Research\MCP\Tools\UpdateEntryToolAction;
use Butschster\ContextGenerator\Research\MCP\Tools\UpdateResearchToolAction;
+use PhpMcp\Schema\Tool;
+use PhpMcp\Schema\ToolAnnotations;
use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Boot\EnvironmentInterface;
use Spiral\Config\ConfiguratorInterface;
@@ -145,20 +147,68 @@ public function defineSingletons(): array
ServerRunner $factory,
ConfigLoaderInterface $loader,
RagRegistryInterface $ragRegistry,
+ ?RagToolRegistryInterface $ragToolRegistry = null,
+ ?RagToolFactory $ragToolFactory = null,
) {
$loader->load();
- foreach ($this->actions($config, $ragRegistry) as $action) {
+ foreach ($this->actions($config, $ragRegistry, $ragToolRegistry) as $action) {
$factory->registerAction($action);
}
+ // Register dynamic RAG tools callback
+ if ($ragToolFactory !== null && $ragToolRegistry !== null && $ragToolRegistry->hasTools()) {
+ $factory->registerDynamicToolRegistrar(
+ function (McpItemsRegistry $registry) use ($ragToolFactory): void {
+ $this->registerDynamicRagTools($registry, $ragToolFactory);
+ },
+ );
+ }
+
return $factory;
},
];
}
- private function actions(McpConfig $config, RagRegistryInterface $ragRegistry): array
- {
+ /**
+ * Register dynamic RAG tools from configuration.
+ */
+ private function registerDynamicRagTools(
+ McpItemsRegistry $registry,
+ RagToolFactory $factory,
+ ): void {
+ $tools = $factory->createAll();
+
+ foreach ($tools['search'] as $action) {
+ $schema = new Tool(
+ name: $action->getToolId(),
+ inputSchema: $action->getInputSchema(),
+ description: $action->getToolDescription(),
+ annotations: new ToolAnnotations(
+ title: $action->getToolName(),
+ ),
+ );
+ $registry->registerDynamicTool($schema);
+ }
+
+ foreach ($tools['store'] as $action) {
+ $schema = new Tool(
+ name: $action->getToolId(),
+ inputSchema: $action->getInputSchema(),
+ description: $action->getToolDescription(),
+ annotations: new ToolAnnotations(
+ title: $action->getToolName(),
+ ),
+ );
+ $registry->registerDynamicTool($schema);
+ }
+ }
+
+ private function actions(
+ McpConfig $config,
+ RagRegistryInterface $ragRegistry,
+ ?RagToolRegistryInterface $ragToolRegistry = null,
+ ): array {
$actions = [
// Prompts controllers
GetPromptAction::class,
@@ -248,13 +298,6 @@ private function actions(McpConfig $config, RagRegistryInterface $ragRegistry):
$actions[] = GitCommitAction::class;
}
- // RAG Tools - only if enabled in context.yaml
- if ($ragRegistry->isEnabled()) {
- $actions[] = RagStoreAction::class;
- $actions[] = RagSearchAction::class;
- $actions[] = RagManageAction::class;
- }
-
// Should be last
if ($config->isCustomToolsEnabled()) {
$actions = [
diff --git a/tests/src/Unit/Rag/Config/CollectionConfigTest.php b/tests/src/Unit/Rag/Config/CollectionConfigTest.php
new file mode 100644
index 00000000..d8b03290
--- /dev/null
+++ b/tests/src/Unit/Rag/Config/CollectionConfigTest.php
@@ -0,0 +1,211 @@
+assertSame('docs', $config->name);
+ $this->assertSame('default', $config->server);
+ $this->assertSame('project_docs', $config->collection);
+ $this->assertNull($config->description);
+ $this->assertNull($config->embeddingsDimension);
+ $this->assertNull($config->embeddingsDistance);
+ $this->assertNull($config->transformer);
+ }
+
+ #[Test]
+ public function it_should_create_instance_with_all_values(): void
+ {
+ $transformer = new TransformerConfig(chunkSize: 2000, overlap: 400);
+
+ $config = new CollectionConfig(
+ name: 'architecture',
+ server: 'cloud',
+ collection: 'arch_docs',
+ description: 'Architecture documentation',
+ embeddingsDimension: 3072,
+ embeddingsDistance: 'Dot',
+ transformer: $transformer,
+ );
+
+ $this->assertSame('architecture', $config->name);
+ $this->assertSame('cloud', $config->server);
+ $this->assertSame('arch_docs', $config->collection);
+ $this->assertSame('Architecture documentation', $config->description);
+ $this->assertSame(3072, $config->embeddingsDimension);
+ $this->assertSame('Dot', $config->embeddingsDistance);
+ $this->assertSame($transformer, $config->transformer);
+ }
+
+ #[Test]
+ public function it_should_create_instance_from_array_with_minimal_data(): void
+ {
+ $config = CollectionConfig::fromArray('test', [
+ 'server' => 'default',
+ 'collection' => 'test_collection',
+ ]);
+
+ $this->assertSame('test', $config->name);
+ $this->assertSame('default', $config->server);
+ $this->assertSame('test_collection', $config->collection);
+ $this->assertNull($config->description);
+ $this->assertNull($config->transformer);
+ }
+
+ #[Test]
+ public function it_should_create_instance_from_array_with_all_values(): void
+ {
+ $config = CollectionConfig::fromArray('docs', [
+ 'server' => 'production',
+ 'collection' => 'prod_docs',
+ 'description' => 'Production documentation',
+ 'embeddings_dimension' => 2048,
+ 'embeddings_distance' => 'Euclid',
+ 'transformer' => [
+ 'chunk_size' => 1500,
+ 'overlap' => 300,
+ ],
+ ]);
+
+ $this->assertSame('docs', $config->name);
+ $this->assertSame('production', $config->server);
+ $this->assertSame('prod_docs', $config->collection);
+ $this->assertSame('Production documentation', $config->description);
+ $this->assertSame(2048, $config->embeddingsDimension);
+ $this->assertSame('Euclid', $config->embeddingsDistance);
+ $this->assertNotNull($config->transformer);
+ $this->assertSame(1500, $config->transformer->chunkSize);
+ $this->assertSame(300, $config->transformer->overlap);
+ }
+
+ #[Test]
+ public function it_should_use_name_as_collection_when_not_specified(): void
+ {
+ $config = CollectionConfig::fromArray('my-collection', [
+ 'server' => 'default',
+ ]);
+
+ $this->assertSame('my-collection', $config->collection);
+ }
+
+ #[Test]
+ public function it_should_use_default_server_when_not_specified(): void
+ {
+ $config = CollectionConfig::fromArray('test', [
+ 'collection' => 'test_col',
+ ]);
+
+ $this->assertSame('default', $config->server);
+ }
+
+ #[Test]
+ public function it_should_return_fallback_transformer_when_no_override(): void
+ {
+ $config = new CollectionConfig(
+ name: 'docs',
+ server: 'default',
+ collection: 'docs',
+ );
+
+ $fallback = new TransformerConfig(chunkSize: 1000, overlap: 200);
+ $result = $config->getTransformer($fallback);
+
+ $this->assertSame($fallback, $result);
+ }
+
+ #[Test]
+ public function it_should_return_collection_transformer_when_specified(): void
+ {
+ $collectionTransformer = new TransformerConfig(chunkSize: 2000, overlap: 400);
+
+ $config = new CollectionConfig(
+ name: 'docs',
+ server: 'default',
+ collection: 'docs',
+ transformer: $collectionTransformer,
+ );
+
+ $fallback = new TransformerConfig(chunkSize: 1000, overlap: 200);
+ $result = $config->getTransformer($fallback);
+
+ $this->assertSame($collectionTransformer, $result);
+ $this->assertNotSame($fallback, $result);
+ }
+
+ #[Test]
+ public function it_should_get_effective_embeddings_dimension_from_collection(): void
+ {
+ $server = new ServerConfig(name: 'default', embeddingsDimension: 1536);
+
+ $config = new CollectionConfig(
+ name: 'docs',
+ server: 'default',
+ collection: 'docs',
+ embeddingsDimension: 3072,
+ );
+
+ $this->assertSame(3072, $config->getEffectiveEmbeddingsDimension($server));
+ }
+
+ #[Test]
+ public function it_should_get_effective_embeddings_dimension_from_server_when_not_overridden(): void
+ {
+ $server = new ServerConfig(name: 'default', embeddingsDimension: 1536);
+
+ $config = new CollectionConfig(
+ name: 'docs',
+ server: 'default',
+ collection: 'docs',
+ );
+
+ $this->assertSame(1536, $config->getEffectiveEmbeddingsDimension($server));
+ }
+
+ #[Test]
+ public function it_should_get_effective_embeddings_distance_from_collection(): void
+ {
+ $server = new ServerConfig(name: 'default', embeddingsDistance: 'Cosine');
+
+ $config = new CollectionConfig(
+ name: 'docs',
+ server: 'default',
+ collection: 'docs',
+ embeddingsDistance: 'Dot',
+ );
+
+ $this->assertSame('Dot', $config->getEffectiveEmbeddingsDistance($server));
+ }
+
+ #[Test]
+ public function it_should_get_effective_embeddings_distance_from_server_when_not_overridden(): void
+ {
+ $server = new ServerConfig(name: 'default', embeddingsDistance: 'Cosine');
+
+ $config = new CollectionConfig(
+ name: 'docs',
+ server: 'default',
+ collection: 'docs',
+ );
+
+ $this->assertSame('Cosine', $config->getEffectiveEmbeddingsDistance($server));
+ }
+}
diff --git a/tests/src/Unit/Rag/Config/RagConfigTest.php b/tests/src/Unit/Rag/Config/RagConfigTest.php
new file mode 100644
index 00000000..f70e16cd
--- /dev/null
+++ b/tests/src/Unit/Rag/Config/RagConfigTest.php
@@ -0,0 +1,283 @@
+assertFalse($config->enabled);
+ $this->assertEmpty($config->servers);
+ $this->assertEmpty($config->collections);
+ $this->assertNull($config->store);
+ $this->assertFalse($config->isLegacyFormat());
+ }
+
+ #[Test]
+ public function it_should_parse_legacy_format_with_store_key(): void
+ {
+ $config = RagConfig::fromArray([
+ 'enabled' => true,
+ 'store' => [
+ 'driver' => 'qdrant',
+ 'qdrant' => [
+ 'endpoint_url' => 'http://localhost:6333',
+ 'api_key' => 'test-key',
+ 'collection' => 'my_collection',
+ 'embeddings_dimension' => 1536,
+ 'embeddings_distance' => 'Cosine',
+ ],
+ ],
+ 'vectorizer' => [
+ 'platform' => 'openai',
+ 'model' => 'text-embedding-3-small',
+ 'api_key' => 'openai-key',
+ ],
+ 'transformer' => [
+ 'chunk_size' => 1000,
+ 'overlap' => 200,
+ ],
+ ]);
+
+ $this->assertTrue($config->enabled);
+ $this->assertTrue($config->isLegacyFormat());
+
+ // Legacy store should be preserved
+ $this->assertNotNull($config->store);
+ $this->assertSame('my_collection', $config->store->collection);
+
+ // Should have converted to new format internally
+ $this->assertArrayHasKey('default', $config->servers);
+ $this->assertArrayHasKey('default', $config->collections);
+
+ $server = $config->getServer('default');
+ $this->assertSame('qdrant', $server->driver);
+ $this->assertSame('http://localhost:6333', $server->endpointUrl);
+ $this->assertSame('test-key', $server->apiKey);
+
+ $collection = $config->getCollection('default');
+ $this->assertSame('default', $collection->server);
+ $this->assertSame('my_collection', $collection->collection);
+ }
+
+ #[Test]
+ public function it_should_parse_new_format_with_servers_and_collections(): void
+ {
+ $config = RagConfig::fromArray([
+ 'enabled' => true,
+ 'servers' => [
+ 'local' => [
+ 'driver' => 'qdrant',
+ 'endpoint_url' => 'http://localhost:6333',
+ ],
+ 'cloud' => [
+ 'driver' => 'qdrant',
+ 'endpoint_url' => 'https://my-cluster.qdrant.io',
+ 'api_key' => 'cloud-key',
+ ],
+ ],
+ 'collections' => [
+ 'docs' => [
+ 'server' => 'local',
+ 'collection' => 'project_docs',
+ 'description' => 'Project documentation',
+ ],
+ 'architecture' => [
+ 'server' => 'cloud',
+ 'collection' => 'arch_decisions',
+ 'description' => 'Architecture decisions',
+ 'transformer' => [
+ 'chunk_size' => 2000,
+ 'overlap' => 400,
+ ],
+ ],
+ ],
+ 'vectorizer' => [
+ 'platform' => 'openai',
+ 'model' => 'text-embedding-3-large',
+ ],
+ 'transformer' => [
+ 'chunk_size' => 1000,
+ 'overlap' => 200,
+ ],
+ ]);
+
+ $this->assertTrue($config->enabled);
+ $this->assertFalse($config->isLegacyFormat());
+ $this->assertNull($config->store);
+
+ // Check servers
+ $this->assertCount(2, $config->servers);
+ $this->assertSame(['local', 'cloud'], $config->getServerNames());
+
+ $localServer = $config->getServer('local');
+ $this->assertSame('http://localhost:6333', $localServer->endpointUrl);
+
+ $cloudServer = $config->getServer('cloud');
+ $this->assertSame('https://my-cluster.qdrant.io', $cloudServer->endpointUrl);
+ $this->assertSame('cloud-key', $cloudServer->apiKey);
+
+ // Check collections
+ $this->assertCount(2, $config->collections);
+ $this->assertSame(['docs', 'architecture'], $config->getCollectionNames());
+
+ $docsCollection = $config->getCollection('docs');
+ $this->assertSame('local', $docsCollection->server);
+ $this->assertSame('project_docs', $docsCollection->collection);
+ $this->assertSame('Project documentation', $docsCollection->description);
+
+ $archCollection = $config->getCollection('architecture');
+ $this->assertSame('cloud', $archCollection->server);
+ $this->assertNotNull($archCollection->transformer);
+ $this->assertSame(2000, $archCollection->transformer->chunkSize);
+ }
+
+ #[Test]
+ public function it_should_enable_rag_when_servers_collections_defined_without_enabled_flag(): void
+ {
+ $config = RagConfig::fromArray([
+ 'servers' => [
+ 'default' => ['endpoint_url' => 'http://localhost:6333'],
+ ],
+ 'collections' => [
+ 'docs' => ['server' => 'default', 'collection' => 'docs'],
+ ],
+ ]);
+
+ $this->assertTrue($config->enabled);
+ }
+
+ #[Test]
+ public function it_should_get_server_for_collection(): void
+ {
+ $config = RagConfig::fromArray([
+ 'servers' => [
+ 'production' => [
+ 'endpoint_url' => 'https://prod.qdrant.io',
+ 'api_key' => 'prod-key',
+ ],
+ ],
+ 'collections' => [
+ 'knowledge' => [
+ 'server' => 'production',
+ 'collection' => 'prod_knowledge',
+ ],
+ ],
+ ]);
+
+ $server = $config->getServerForCollection('knowledge');
+
+ $this->assertSame('production', $server->name);
+ $this->assertSame('https://prod.qdrant.io', $server->endpointUrl);
+ }
+
+ #[Test]
+ public function it_should_throw_exception_for_unknown_server(): void
+ {
+ $config = new RagConfig();
+
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Server "unknown" not found');
+
+ $config->getServer('unknown');
+ }
+
+ #[Test]
+ public function it_should_throw_exception_for_unknown_collection(): void
+ {
+ $config = new RagConfig();
+
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Collection "unknown" not found');
+
+ $config->getCollection('unknown');
+ }
+
+ #[Test]
+ public function it_should_check_if_collection_exists(): void
+ {
+ $config = RagConfig::fromArray([
+ 'collections' => [
+ 'docs' => ['server' => 'default', 'collection' => 'docs'],
+ ],
+ ]);
+
+ $this->assertTrue($config->hasCollection('docs'));
+ $this->assertFalse($config->hasCollection('unknown'));
+ }
+
+ #[Test]
+ public function it_should_parse_vectorizer_config(): void
+ {
+ $config = RagConfig::fromArray([
+ 'vectorizer' => [
+ 'platform' => 'openai',
+ 'model' => 'text-embedding-3-large',
+ 'api_key' => 'my-api-key',
+ ],
+ ]);
+
+ $this->assertSame('openai', $config->vectorizer->platform);
+ $this->assertSame('text-embedding-3-large', $config->vectorizer->model);
+ $this->assertSame('my-api-key', $config->vectorizer->apiKey);
+ }
+
+ #[Test]
+ public function it_should_parse_transformer_config(): void
+ {
+ $config = RagConfig::fromArray([
+ 'transformer' => [
+ 'chunk_size' => 2000,
+ 'overlap' => 500,
+ ],
+ ]);
+
+ $this->assertSame(2000, $config->transformer->chunkSize);
+ $this->assertSame(500, $config->transformer->overlap);
+ }
+
+ #[Test]
+ public function it_should_use_default_values_for_empty_array(): void
+ {
+ $config = RagConfig::fromArray([]);
+
+ $this->assertFalse($config->enabled);
+ $this->assertEmpty($config->servers);
+ $this->assertEmpty($config->collections);
+ $this->assertSame('openai', $config->vectorizer->platform);
+ $this->assertSame('text-embedding-3-small', $config->vectorizer->model);
+ $this->assertSame(1000, $config->transformer->chunkSize);
+ $this->assertSame(200, $config->transformer->overlap);
+ }
+
+ #[Test]
+ public function it_should_handle_integer_server_names(): void
+ {
+ $config = RagConfig::fromArray([
+ 'servers' => [
+ 0 => ['endpoint_url' => 'http://server0:6333'],
+ 1 => ['endpoint_url' => 'http://server1:6333'],
+ ],
+ 'collections' => [
+ 0 => ['server' => '0', 'collection' => 'col0'],
+ ],
+ ]);
+
+ $this->assertCount(2, $config->servers);
+ $this->assertSame([0, 1], $config->getServerNames());
+
+ $server = $config->getServer('0');
+ $this->assertSame('http://server0:6333', $server->endpointUrl);
+ }
+}
diff --git a/tests/src/Unit/Rag/Config/ServerConfigTest.php b/tests/src/Unit/Rag/Config/ServerConfigTest.php
new file mode 100644
index 00000000..3d259cce
--- /dev/null
+++ b/tests/src/Unit/Rag/Config/ServerConfigTest.php
@@ -0,0 +1,104 @@
+assertSame('test', $config->name);
+ $this->assertSame('qdrant', $config->driver);
+ $this->assertSame('http://localhost:6333', $config->endpointUrl);
+ $this->assertSame('', $config->apiKey);
+ $this->assertSame(1536, $config->embeddingsDimension);
+ $this->assertSame('Cosine', $config->embeddingsDistance);
+ }
+
+ #[Test]
+ public function it_should_create_instance_with_custom_values(): void
+ {
+ $config = new ServerConfig(
+ name: 'cloud',
+ driver: 'qdrant',
+ endpointUrl: 'https://my-cluster.qdrant.io',
+ apiKey: 'secret-key',
+ embeddingsDimension: 3072,
+ embeddingsDistance: 'Dot',
+ );
+
+ $this->assertSame('cloud', $config->name);
+ $this->assertSame('qdrant', $config->driver);
+ $this->assertSame('https://my-cluster.qdrant.io', $config->endpointUrl);
+ $this->assertSame('secret-key', $config->apiKey);
+ $this->assertSame(3072, $config->embeddingsDimension);
+ $this->assertSame('Dot', $config->embeddingsDistance);
+ }
+
+ #[Test]
+ public function it_should_create_instance_from_array_with_defaults(): void
+ {
+ $config = ServerConfig::fromArray('default', []);
+
+ $this->assertSame('default', $config->name);
+ $this->assertSame('qdrant', $config->driver);
+ $this->assertSame('http://localhost:6333', $config->endpointUrl);
+ $this->assertSame('', $config->apiKey);
+ $this->assertSame(1536, $config->embeddingsDimension);
+ $this->assertSame('Cosine', $config->embeddingsDistance);
+ }
+
+ #[Test]
+ public function it_should_create_instance_from_array_with_all_values(): void
+ {
+ $config = ServerConfig::fromArray('production', [
+ 'driver' => 'qdrant',
+ 'endpoint_url' => 'https://prod.qdrant.io',
+ 'api_key' => 'prod-api-key',
+ 'embeddings_dimension' => 2048,
+ 'embeddings_distance' => 'Euclid',
+ ]);
+
+ $this->assertSame('production', $config->name);
+ $this->assertSame('qdrant', $config->driver);
+ $this->assertSame('https://prod.qdrant.io', $config->endpointUrl);
+ $this->assertSame('prod-api-key', $config->apiKey);
+ $this->assertSame(2048, $config->embeddingsDimension);
+ $this->assertSame('Euclid', $config->embeddingsDistance);
+ }
+
+ #[Test]
+ public function it_should_handle_partial_array_data(): void
+ {
+ $config = ServerConfig::fromArray('partial', [
+ 'endpoint_url' => 'http://custom:6333',
+ ]);
+
+ $this->assertSame('partial', $config->name);
+ $this->assertSame('qdrant', $config->driver);
+ $this->assertSame('http://custom:6333', $config->endpointUrl);
+ $this->assertSame('', $config->apiKey);
+ $this->assertSame(1536, $config->embeddingsDimension);
+ $this->assertSame('Cosine', $config->embeddingsDistance);
+ }
+
+ #[Test]
+ public function it_should_cast_numeric_string_to_integer_for_dimension(): void
+ {
+ $config = ServerConfig::fromArray('test', [
+ 'embeddings_dimension' => '3072',
+ ]);
+
+ $this->assertSame(3072, $config->embeddingsDimension);
+ }
+}