From d1edd5cb294f29e070a4477830035da15b1dd10e Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:32:18 -0400 Subject: [PATCH 01/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 1 Rename McpServer domain to ConcreteServer Co-Authored-By: Claude Opus 5.5 (1M context) --- AGENTS.md | 4 ++-- config/cortex.php | 8 ++++---- database/factories/McpInstructionFactory.php | 2 +- .../McpInstructionVersionFactory.php | 4 ++-- phpunit.xml.dist | 5 +++++ .../views/ui/servers/instructions.blade.php | 2 +- src/Atrium/CortexPlugin.php | 2 +- .../McpInstructionUiController.php | 14 ++++++------- .../Http/Controllers/ServerUiController.php | 4 ++-- src/Atrium/ScreenAccess.php | 2 +- src/Cortex.php | 2 +- .../CreateMcpInstructionVersionAction.php | 12 +++++------ .../Actions/DeleteMcpInstructionAction.php | 8 ++++---- .../ListMcpInstructionVersionsAction.php | 10 +++++----- .../Actions/ListMcpServersAction.php | 8 ++++---- .../PublishMcpInstructionVersionAction.php | 10 +++++----- .../Actions/ShowMcpInstructionAction.php | 8 ++++---- .../Concerns/HasVersionedInstructions.php | 8 ++++---- .../ConcreteServerServiceProvider.php} | 8 ++++---- .../Data/CreateMcpInstructionVersionData.php | 2 +- .../Events/McpInstructionCreatedEvent.php | 4 ++-- .../Events/McpInstructionCreatingEvent.php | 4 ++-- .../McpInstructionDeletedActionEvent.php | 4 ++-- .../Events/McpInstructionDeletedEvent.php | 4 ++-- .../McpInstructionDeletingActionEvent.php | 4 ++-- .../Events/McpInstructionDeletingEvent.php | 4 ++-- .../Events/McpInstructionReplicatingEvent.php | 4 ++-- .../Events/McpInstructionRetrievedEvent.php | 4 ++-- .../Events/McpInstructionSavedEvent.php | 4 ++-- .../Events/McpInstructionSavingEvent.php | 4 ++-- .../McpInstructionShowingActionEvent.php | 2 +- .../Events/McpInstructionShownActionEvent.php | 4 ++-- .../Events/McpInstructionUpdatedEvent.php | 4 ++-- .../Events/McpInstructionUpdatingEvent.php | 4 ++-- ...cpInstructionVersionCreatedActionEvent.php | 4 ++-- .../McpInstructionVersionCreatedEvent.php | 4 ++-- ...pInstructionVersionCreatingActionEvent.php | 4 ++-- .../McpInstructionVersionCreatingEvent.php | 4 ++-- .../McpInstructionVersionDeletedEvent.php | 4 ++-- .../McpInstructionVersionDeletingEvent.php | 4 ++-- ...InstructionVersionPublishedActionEvent.php | 4 ++-- ...nstructionVersionPublishingActionEvent.php | 4 ++-- .../McpInstructionVersionReplicatingEvent.php | 4 ++-- .../McpInstructionVersionRetrievedEvent.php | 4 ++-- .../McpInstructionVersionSavedEvent.php | 4 ++-- .../McpInstructionVersionSavingEvent.php | 4 ++-- .../McpInstructionVersionUpdatedEvent.php | 4 ++-- .../McpInstructionVersionUpdatingEvent.php | 4 ++-- ...cpInstructionVersionsListedActionEvent.php | 6 +++--- ...pInstructionVersionsListingActionEvent.php | 4 ++-- .../Events/McpServersListedActionEvent.php | 2 +- .../Events/McpServersListingActionEvent.php | 2 +- .../Exceptions/McpServerNotFoundException.php | 2 +- .../Controllers/McpInstructionController.php | 12 +++++------ .../Http/Controllers/McpServerController.php | 4 ++-- .../Requests/DeleteMcpInstructionRequest.php | 4 ++-- .../IndexMcpInstructionVersionsRequest.php | 8 ++++---- .../Http/Requests/IndexMcpServersRequest.php | 6 +++--- .../Http/Requests/McpInstructionRequest.php | 8 ++++---- .../PublishMcpInstructionVersionRequest.php | 6 +++--- .../Requests/ShowMcpInstructionRequest.php | 6 +++--- .../StoreMcpInstructionVersionRequest.php | 10 +++++----- .../Http/Resources/McpServerResource.php | 2 +- ...eateServerInstructionVersionMcpRequest.php | 10 +++++----- .../DeleteServerInstructionsMcpRequest.php | 4 ++-- ...istServerInstructionVersionsMcpRequest.php | 8 ++++---- .../Mcp/Requests/ListServersMcpRequest.php | 6 +++--- ...lishServerInstructionVersionMcpRequest.php | 6 +++--- .../Mcp/Requests/ServerMcpRequest.php | 8 ++++---- .../ShowServerInstructionsMcpRequest.php | 6 +++--- .../CreateServerInstructionVersionTool.php | 6 +++--- .../Tools/DeleteServerInstructionsTool.php | 4 ++-- .../ListServerInstructionVersionsTool.php | 6 +++--- .../Mcp/Tools/ListServersTool.php | 6 +++--- .../PublishServerInstructionVersionTool.php | 6 +++--- .../Mcp/Tools/ShowServerInstructionsTool.php | 6 +++--- .../Models/McpInstructionModel.php | 2 +- .../Models/McpInstructionVersionModel.php | 2 +- .../Policies/McpInstructionPolicy.php | 4 ++-- .../Policies/McpInstructionVersionPolicy.php | 6 +++--- .../Resources/McpInstructionResource.php | 4 ++-- .../McpInstructionVersionResource.php | 4 ++-- .../Services/McpInstructionOverrides.php | 4 ++-- .../Services/McpServerRegistry.php | 4 ++-- .../Support/Server.php | 4 ++-- .../{McpServer => ConcreteServer}/routes.php | 4 ++-- src/Domains/DomainServiceProvider.php | 4 ++-- src/Facades/Cortex.php | 2 +- src/Mcp/CortexServer.php | 12 +++++------ tests/Feature/EventsTest.php | 14 ++++++------- tests/Feature/Http/McpInstructionsTest.php | 6 +++--- .../Mcp/ServerInstructionToolsTest.php | 16 +++++++-------- tests/Feature/McpServerRegistryTest.php | 20 +++++++++++++++---- tests/Feature/ModelsTest.php | 4 ++-- tests/Feature/PerformanceTest.php | 4 ++-- tests/Feature/PolicyTest.php | 10 +++++----- tests/Feature/PublicationCacheTest.php | 12 +++++------ tests/Feature/ServerBaseTest.php | 4 ++-- tests/Feature/Ui/ScreenControlsTest.php | 2 +- tests/Fixtures/EchoServer.php | 2 +- tests/Fixtures/PlainServer.php | 2 +- .../Policies/GrantedMcpInstructionPolicy.php | 4 ++-- .../Policies/SignedInMcpInstructionPolicy.php | 2 +- .../Modes/RenamedTables/RenamedTablesTest.php | 4 ++-- workbench/app/Mcp/Servers/CatalogServer.php | 2 +- workbench/app/Mcp/Servers/SupportServer.php | 2 +- workbench/database/seeders/DatabaseSeeder.php | 4 ++-- 107 files changed, 292 insertions(+), 275 deletions(-) rename src/Domains/{McpServer => ConcreteServer}/Actions/CreateMcpInstructionVersionAction.php (77%) rename src/Domains/{McpServer => ConcreteServer}/Actions/DeleteMcpInstructionAction.php (70%) rename src/Domains/{McpServer => ConcreteServer}/Actions/ListMcpInstructionVersionsAction.php (64%) rename src/Domains/{McpServer => ConcreteServer}/Actions/ListMcpServersAction.php (69%) rename src/Domains/{McpServer => ConcreteServer}/Actions/PublishMcpInstructionVersionAction.php (74%) rename src/Domains/{McpServer => ConcreteServer}/Actions/ShowMcpInstructionAction.php (64%) rename src/Domains/{McpServer => ConcreteServer}/Concerns/HasVersionedInstructions.php (77%) rename src/Domains/{McpServer/McpServerServiceProvider.php => ConcreteServer/ConcreteServerServiceProvider.php} (56%) rename src/Domains/{McpServer => ConcreteServer}/Data/CreateMcpInstructionVersionData.php (91%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionCreatedEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionCreatingEvent.php (82%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionDeletedActionEvent.php (78%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionDeletedEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionDeletingActionEvent.php (77%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionDeletingEvent.php (82%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionReplicatingEvent.php (82%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionRetrievedEvent.php (82%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionSavedEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionSavingEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionShowingActionEvent.php (87%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionShownActionEvent.php (77%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionUpdatedEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionUpdatingEvent.php (82%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionCreatedActionEvent.php (78%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionCreatedEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionCreatingActionEvent.php (78%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionCreatingEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionDeletedEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionDeletingEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionPublishedActionEvent.php (79%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionPublishingActionEvent.php (79%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionReplicatingEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionRetrievedEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionSavedEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionSavingEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionUpdatedEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionUpdatingEvent.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionsListedActionEvent.php (74%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpInstructionVersionsListingActionEvent.php (78%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpServersListedActionEvent.php (88%) rename src/Domains/{McpServer => ConcreteServer}/Events/McpServersListingActionEvent.php (85%) rename src/Domains/{McpServer => ConcreteServer}/Exceptions/McpServerNotFoundException.php (80%) rename src/Domains/{McpServer => ConcreteServer}/Http/Controllers/McpInstructionController.php (61%) rename src/Domains/{McpServer => ConcreteServer}/Http/Controllers/McpServerController.php (58%) rename src/Domains/{McpServer => ConcreteServer}/Http/Requests/DeleteMcpInstructionRequest.php (73%) rename src/Domains/{McpServer => ConcreteServer}/Http/Requests/IndexMcpInstructionVersionsRequest.php (61%) rename src/Domains/{McpServer => ConcreteServer}/Http/Requests/IndexMcpServersRequest.php (60%) rename src/Domains/{McpServer => ConcreteServer}/Http/Requests/McpInstructionRequest.php (82%) rename src/Domains/{McpServer => ConcreteServer}/Http/Requests/PublishMcpInstructionVersionRequest.php (69%) rename src/Domains/{McpServer => ConcreteServer}/Http/Requests/ShowMcpInstructionRequest.php (66%) rename src/Domains/{McpServer => ConcreteServer}/Http/Requests/StoreMcpInstructionVersionRequest.php (63%) rename src/Domains/{McpServer => ConcreteServer}/Http/Resources/McpServerResource.php (92%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Requests/CreateServerInstructionVersionMcpRequest.php (65%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Requests/DeleteServerInstructionsMcpRequest.php (78%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Requests/ListServerInstructionVersionsMcpRequest.php (66%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Requests/ListServersMcpRequest.php (62%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Requests/PublishServerInstructionVersionMcpRequest.php (73%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Requests/ServerMcpRequest.php (87%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Requests/ShowServerInstructionsMcpRequest.php (71%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Tools/CreateServerInstructionVersionTool.php (81%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Tools/DeleteServerInstructionsTool.php (82%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Tools/ListServerInstructionVersionsTool.php (78%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Tools/ListServersTool.php (77%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Tools/PublishServerInstructionVersionTool.php (80%) rename src/Domains/{McpServer => ConcreteServer}/Mcp/Tools/ShowServerInstructionsTool.php (78%) rename src/Domains/{McpServer => ConcreteServer}/Models/McpInstructionModel.php (96%) rename src/Domains/{McpServer => ConcreteServer}/Models/McpInstructionVersionModel.php (96%) rename src/Domains/{McpServer => ConcreteServer}/Policies/McpInstructionPolicy.php (87%) rename src/Domains/{McpServer => ConcreteServer}/Policies/McpInstructionVersionPolicy.php (83%) rename src/Domains/{McpServer => ConcreteServer}/Resources/McpInstructionResource.php (89%) rename src/Domains/{McpServer => ConcreteServer}/Resources/McpInstructionVersionResource.php (86%) rename src/Domains/{McpServer => ConcreteServer}/Services/McpInstructionOverrides.php (90%) rename src/Domains/{McpServer => ConcreteServer}/Services/McpServerRegistry.php (96%) rename src/Domains/{McpServer => ConcreteServer}/Support/Server.php (77%) rename src/Domains/{McpServer => ConcreteServer}/routes.php (83%) diff --git a/AGENTS.md b/AGENTS.md index d48fda0..88bf0c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ This repository is a Laravel package. Keep the package focused, idiomatic, and e ## Layout -The package follows the mono domain-module layout, described in `agent-os/standards/backend/domain-modules.md`. Code lives in `src/Domains/{VirtualAgent,ConcreteAgent,Tool,McpServer,RedirectDomain}` (namespace `RefactorCircus\Cortex\Domains\{Domain}`), each with its own `{Domain}ServiceProvider` registered by `Domains\DomainServiceProvider`. Models are named `{Entity}Model`. The Atrium screens span every domain and live in `src/Atrium`; package-wide pieces (`Cortex`, the facade, the base requests, `Mcp\CortexServer`, `Support\`) stay at the top level. `config/cortex.php` stays one file. +The package follows the mono domain-module layout, described in `agent-os/standards/backend/domain-modules.md`. Code lives in `src/Domains/{VirtualAgent,ConcreteAgent,Tool,ConcreteServer,RedirectDomain}` (namespace `RefactorCircus\Cortex\Domains\{Domain}`), each with its own `{Domain}ServiceProvider` registered by `Domains\DomainServiceProvider`. Models are named `{Entity}Model`. The Atrium screens span every domain and live in `src/Atrium`; package-wide pieces (`Cortex`, the facade, the base requests, `Mcp\CortexServer`, `Support\`) stay at the top level. `config/cortex.php` stays one file. ## Keystone @@ -24,7 +24,7 @@ Cortex stands on `refactor-circus/keystone`, the shared runtime of the Refactor - Action input is a `final readonly` `{Action}Data` in the domain's `Data/` (on `RefactorCircus\Keystone\Data\Data`), never an array: fields are promoted constructor properties (camelCase of the input keys; `T|Missing = new Missing` for partial updates), `rules()` lives on the Data (with any context args, e.g. `UpdateConcreteAgentToolsData::rules($agent)`), and the starting/finished events that took input carry the Data. List Data expose `pagination()` (Keystone's `Pagination`) and add its rules; their tools add `ListXData::pagination()->schema($schema)`. HTTP and MCP requests validate once: their `rules()` return the identifier rules (`agentRules()`, `versionRules()`, `serverRules()`, `ownerRules()`, `domainRules()` on the MCP and redirect-domain bases) plus `XData::rules(...)`, and `persist()`/`handle()` build with `XData::fromValidated($this->validated() / $validated)` - never `XData::from()` in a request (ArchTest). Atrium controllers use `XData::from($request->all(), ...context)`, which validates; code that vouches for its values uses `new XData(...)`. - API resources extend `RefactorCircus\Keystone\Http\Resources\JsonResource` and declare `schema(JsonSchema $schema)` next to `toArray()` (always-present fields `required()`, conditional ones not, `nullable()` where null is possible). MCP requests answer with `(new XResource($m))->toStructuredResponse()` / `XResource::collection($page)->toStructuredResponse()`, and each tool that answers with structured content declares `outputSchema()` as `XResource::structuredSchema($schema)` / `collectionSchema($schema, ListXData::pagination())` (unpaginated lists declare `data` alone). `mcpTool()` in tests is Keystone's `Testing\McpTools::call()`, which checks every structured answer against the tool's schema, and `tests/Feature/Mcp/OutputSchemaTest.php` requires the declaration. - `Http\Request` and `Mcp\Request` extend Keystone's request bases but keep Cortex's authorization: every check goes to the Gate, as the signed-in user or as a guest, and the bundled policies allow guests. Do not switch them to Keystone's `authorization` switch. A guest refused over HTTP gets 401 (Keystone's base), a signed-in user 403. `ConcreteAgentMcpRequest` and `ServerMcpRequest` throw `ModelNotFoundException` for unknown names on purpose, so they answer the base request's `Not found.`. -- `Mcp\CortexServer` extends `RefactorCircus\Keystone\Mcp\Server` and lists every tool in `TOOLS`, including `Mcp\Tools\ListCortexHistoryTool`. Cortex's own tools extend `RefactorCircus\Keystone\Mcp\Tool`; `Domains\Tool\Support\Tool` and `Domains\McpServer\Support\Server` are for application tools and servers. +- `Mcp\CortexServer` extends `RefactorCircus\Keystone\Mcp\Server` and lists every tool in `TOOLS`, including `Mcp\Tools\ListCortexHistoryTool`. Cortex's own tools extend `RefactorCircus\Keystone\Mcp\Tool`; `Domains\Tool\Support\Tool` and `Domains\ConcreteServer\Support\Server` are for application tools and servers. ## Frontend diff --git a/config/cortex.php b/config/cortex.php index d2250c6..74fc844 100644 --- a/config/cortex.php +++ b/config/cortex.php @@ -7,10 +7,10 @@ use RefactorCircus\Cortex\Domains\ConcreteAgent\Models\ConcreteAgentOverrideVersionModel; use RefactorCircus\Cortex\Domains\ConcreteAgent\Policies\ConcreteAgentOverridePolicy; use RefactorCircus\Cortex\Domains\ConcreteAgent\Policies\ConcreteAgentOverrideVersionPolicy; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionPolicy; -use RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionVersionPolicy; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Policies\McpInstructionPolicy; +use RefactorCircus\Cortex\Domains\ConcreteServer\Policies\McpInstructionVersionPolicy; use RefactorCircus\Cortex\Domains\RedirectDomain\Models\RedirectDomainModel; use RefactorCircus\Cortex\Domains\RedirectDomain\Policies\RedirectDomainPolicy; use RefactorCircus\Cortex\Domains\Tool\Models\ToolDescriptionModel; diff --git a/database/factories/McpInstructionFactory.php b/database/factories/McpInstructionFactory.php index 433cefe..29d081f 100644 --- a/database/factories/McpInstructionFactory.php +++ b/database/factories/McpInstructionFactory.php @@ -5,7 +5,7 @@ namespace RefactorCircus\Cortex\Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; /** * @extends Factory diff --git a/database/factories/McpInstructionVersionFactory.php b/database/factories/McpInstructionVersionFactory.php index aa79de5..8738202 100644 --- a/database/factories/McpInstructionVersionFactory.php +++ b/database/factories/McpInstructionVersionFactory.php @@ -5,8 +5,8 @@ namespace RefactorCircus\Cortex\Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; /** * @extends Factory diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 15eeb96..8ab91f1 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -34,4 +34,9 @@ src + + + + + diff --git a/resources/views/ui/servers/instructions.blade.php b/resources/views/ui/servers/instructions.blade.php index dfc7303..9eeeb29 100644 --- a/resources/views/ui/servers/instructions.blade.php +++ b/resources/views/ui/servers/instructions.blade.php @@ -9,7 +9,7 @@ @include('cortex::ui.partials.override', [ 'override' => $instruction, 'subject' => $subject, - 'versionClass' => \RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel::class, + 'versionClass' => \RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel::class, 'fallback' => $codeInstructions, 'versions' => $versions, 'storeRoute' => route('atrium.cortex.servers.instructions.store', $server), diff --git a/src/Atrium/CortexPlugin.php b/src/Atrium/CortexPlugin.php index e0131e7..40114be 100644 --- a/src/Atrium/CortexPlugin.php +++ b/src/Atrium/CortexPlugin.php @@ -25,7 +25,7 @@ use RefactorCircus\Cortex\Atrium\Http\Controllers\VirtualAgentVersionUiController; use RefactorCircus\Cortex\Domains\ConcreteAgent\Models\ConcreteAgentOverrideModel; use RefactorCircus\Cortex\Domains\ConcreteAgent\Services\AgentRegistry; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Domains\RedirectDomain\Models\RedirectDomainModel; use RefactorCircus\Cortex\Domains\Tool\Services\ToolRegistry; use RefactorCircus\Cortex\Domains\VirtualAgent\Models\VirtualAgentModel; diff --git a/src/Atrium/Http/Controllers/McpInstructionUiController.php b/src/Atrium/Http/Controllers/McpInstructionUiController.php index 18e601c..c6061d0 100644 --- a/src/Atrium/Http/Controllers/McpInstructionUiController.php +++ b/src/Atrium/Http/Controllers/McpInstructionUiController.php @@ -9,13 +9,13 @@ use Illuminate\Http\Request; use RefactorCircus\Cortex\Atrium\Http\Controllers\Concerns\AuthorizesScreens; use RefactorCircus\Cortex\Atrium\ScreenAccess; -use RefactorCircus\Cortex\Domains\McpServer\Actions\CreateMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Actions\DeleteMcpInstructionAction; -use RefactorCircus\Cortex\Domains\McpServer\Actions\PublishMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Data\CreateMcpInstructionVersionData; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\CreateMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\DeleteMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\PublishMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; final class McpInstructionUiController { diff --git a/src/Atrium/Http/Controllers/ServerUiController.php b/src/Atrium/Http/Controllers/ServerUiController.php index c8495fd..0d3d767 100644 --- a/src/Atrium/Http/Controllers/ServerUiController.php +++ b/src/Atrium/Http/Controllers/ServerUiController.php @@ -5,8 +5,8 @@ namespace RefactorCircus\Cortex\Atrium\Http\Controllers; use Illuminate\Contracts\View\View; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ListMcpServersAction; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ListMcpServersAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; final class ServerUiController { diff --git a/src/Atrium/ScreenAccess.php b/src/Atrium/ScreenAccess.php index b5ee9a5..2d51e6c 100644 --- a/src/Atrium/ScreenAccess.php +++ b/src/Atrium/ScreenAccess.php @@ -7,7 +7,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Gate; use RefactorCircus\Cortex\Domains\ConcreteAgent\Models\ConcreteAgentOverrideModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Cortex\Domains\Tool\Models\ToolDescriptionModel; /** diff --git a/src/Cortex.php b/src/Cortex.php index a9104db..d064544 100644 --- a/src/Cortex.php +++ b/src/Cortex.php @@ -7,7 +7,7 @@ use Laravel\Ai\Contracts\Agent; use Laravel\Ai\Responses\AgentResponse; use RefactorCircus\Cortex\Domains\ConcreteAgent\Services\AgentRegistry; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Domains\Tool\Services\ToolRegistry; use RefactorCircus\Cortex\Domains\VirtualAgent\Models\VirtualAgentModel; use RefactorCircus\Cortex\Domains\VirtualAgent\Services\AgentFactory; diff --git a/src/Domains/McpServer/Actions/CreateMcpInstructionVersionAction.php b/src/Domains/ConcreteServer/Actions/CreateMcpInstructionVersionAction.php similarity index 77% rename from src/Domains/McpServer/Actions/CreateMcpInstructionVersionAction.php rename to src/Domains/ConcreteServer/Actions/CreateMcpInstructionVersionAction.php index 46c5750..7265482 100644 --- a/src/Domains/McpServer/Actions/CreateMcpInstructionVersionAction.php +++ b/src/Domains/ConcreteServer/Actions/CreateMcpInstructionVersionAction.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Actions; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Actions; use Illuminate\Support\Facades\DB; -use RefactorCircus\Cortex\Domains\McpServer\Data\CreateMcpInstructionVersionData; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionVersionCreatedActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionVersionCreatingActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionVersionCreatedActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionVersionCreatingActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Cortex\Support\PublicationCache; final class CreateMcpInstructionVersionAction diff --git a/src/Domains/McpServer/Actions/DeleteMcpInstructionAction.php b/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php similarity index 70% rename from src/Domains/McpServer/Actions/DeleteMcpInstructionAction.php rename to src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php index 2062eb5..d0295cb 100644 --- a/src/Domains/McpServer/Actions/DeleteMcpInstructionAction.php +++ b/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Actions; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Actions; use Illuminate\Support\Facades\DB; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionDeletedActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionDeletingActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionDeletedActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionDeletingActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Cortex\Support\PublicationCache; final class DeleteMcpInstructionAction diff --git a/src/Domains/McpServer/Actions/ListMcpInstructionVersionsAction.php b/src/Domains/ConcreteServer/Actions/ListMcpInstructionVersionsAction.php similarity index 64% rename from src/Domains/McpServer/Actions/ListMcpInstructionVersionsAction.php rename to src/Domains/ConcreteServer/Actions/ListMcpInstructionVersionsAction.php index 9469f2a..36213e9 100644 --- a/src/Domains/McpServer/Actions/ListMcpInstructionVersionsAction.php +++ b/src/Domains/ConcreteServer/Actions/ListMcpInstructionVersionsAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Actions; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Actions; use Illuminate\Database\Eloquent\Collection; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionVersionsListedActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionVersionsListingActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionVersionsListedActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionVersionsListingActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; final class ListMcpInstructionVersionsAction { diff --git a/src/Domains/McpServer/Actions/ListMcpServersAction.php b/src/Domains/ConcreteServer/Actions/ListMcpServersAction.php similarity index 69% rename from src/Domains/McpServer/Actions/ListMcpServersAction.php rename to src/Domains/ConcreteServer/Actions/ListMcpServersAction.php index ef9a7ce..bd72144 100644 --- a/src/Domains/McpServer/Actions/ListMcpServersAction.php +++ b/src/Domains/ConcreteServer/Actions/ListMcpServersAction.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Actions; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Actions; use Laravel\Mcp\Server as McpServer; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpServersListedActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpServersListingActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpServersListedActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpServersListingActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; final class ListMcpServersAction { diff --git a/src/Domains/McpServer/Actions/PublishMcpInstructionVersionAction.php b/src/Domains/ConcreteServer/Actions/PublishMcpInstructionVersionAction.php similarity index 74% rename from src/Domains/McpServer/Actions/PublishMcpInstructionVersionAction.php rename to src/Domains/ConcreteServer/Actions/PublishMcpInstructionVersionAction.php index f56c991..41fc2c3 100644 --- a/src/Domains/McpServer/Actions/PublishMcpInstructionVersionAction.php +++ b/src/Domains/ConcreteServer/Actions/PublishMcpInstructionVersionAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Actions; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Actions; use Illuminate\Support\Facades\DB; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionVersionPublishedActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionVersionPublishingActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionVersionPublishedActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionVersionPublishingActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Cortex\Support\PublicationCache; final class PublishMcpInstructionVersionAction diff --git a/src/Domains/McpServer/Actions/ShowMcpInstructionAction.php b/src/Domains/ConcreteServer/Actions/ShowMcpInstructionAction.php similarity index 64% rename from src/Domains/McpServer/Actions/ShowMcpInstructionAction.php rename to src/Domains/ConcreteServer/Actions/ShowMcpInstructionAction.php index 8ff8736..4adb241 100644 --- a/src/Domains/McpServer/Actions/ShowMcpInstructionAction.php +++ b/src/Domains/ConcreteServer/Actions/ShowMcpInstructionAction.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Actions; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Actions; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionShowingActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Events\McpInstructionShownActionEvent; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionShowingActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionShownActionEvent; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; final class ShowMcpInstructionAction { diff --git a/src/Domains/McpServer/Concerns/HasVersionedInstructions.php b/src/Domains/ConcreteServer/Concerns/HasVersionedInstructions.php similarity index 77% rename from src/Domains/McpServer/Concerns/HasVersionedInstructions.php rename to src/Domains/ConcreteServer/Concerns/HasVersionedInstructions.php index c23d252..68b33a1 100644 --- a/src/Domains/McpServer/Concerns/HasVersionedInstructions.php +++ b/src/Domains/ConcreteServer/Concerns/HasVersionedInstructions.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Concerns; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Concerns; use Laravel\Mcp\Server\ServerContext; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpInstructionOverrides; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; -use RefactorCircus\Cortex\Domains\McpServer\Support\Server; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpInstructionOverrides; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Support\Server; /** * Serve the published Cortex instructions override, when one exists, in diff --git a/src/Domains/McpServer/McpServerServiceProvider.php b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php similarity index 56% rename from src/Domains/McpServer/McpServerServiceProvider.php rename to src/Domains/ConcreteServer/ConcreteServerServiceProvider.php index bdea1d3..fc26e4e 100644 --- a/src/Domains/McpServer/McpServerServiceProvider.php +++ b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer; +namespace RefactorCircus\Cortex\Domains\ConcreteServer; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpInstructionOverrides; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpInstructionOverrides; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Keystone\Support\ServiceProvider; -class McpServerServiceProvider extends ServiceProvider +class ConcreteServerServiceProvider extends ServiceProvider { public function register(): void { diff --git a/src/Domains/McpServer/Data/CreateMcpInstructionVersionData.php b/src/Domains/ConcreteServer/Data/CreateMcpInstructionVersionData.php similarity index 91% rename from src/Domains/McpServer/Data/CreateMcpInstructionVersionData.php rename to src/Domains/ConcreteServer/Data/CreateMcpInstructionVersionData.php index 09c0146..235ab99 100644 --- a/src/Domains/McpServer/Data/CreateMcpInstructionVersionData.php +++ b/src/Domains/ConcreteServer/Data/CreateMcpInstructionVersionData.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Data; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Data; use RefactorCircus\Keystone\Data\Data; diff --git a/src/Domains/McpServer/Events/McpInstructionCreatedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionCreatedEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionCreatedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionCreatedEvent.php index a158ee1..d58233e 100644 --- a/src/Domains/McpServer/Events/McpInstructionCreatedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionCreatedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionCreatingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionCreatingEvent.php similarity index 82% rename from src/Domains/McpServer/Events/McpInstructionCreatingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionCreatingEvent.php index 6ba1332..a7924bb 100644 --- a/src/Domains/McpServer/Events/McpInstructionCreatingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionCreatingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionDeletedActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionDeletedActionEvent.php similarity index 78% rename from src/Domains/McpServer/Events/McpInstructionDeletedActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionDeletedActionEvent.php index 3dc791b..89ef5dc 100644 --- a/src/Domains/McpServer/Events/McpInstructionDeletedActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionDeletedActionEvent.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ActionFinishedEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionDeletedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionDeletedEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionDeletedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionDeletedEvent.php index 35f4d2e..e7d0291 100644 --- a/src/Domains/McpServer/Events/McpInstructionDeletedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionDeletedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionDeletingActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionDeletingActionEvent.php similarity index 77% rename from src/Domains/McpServer/Events/McpInstructionDeletingActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionDeletingActionEvent.php index 2f025eb..c6f51fc 100644 --- a/src/Domains/McpServer/Events/McpInstructionDeletingActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionDeletingActionEvent.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ActionStartingEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionDeletingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionDeletingEvent.php similarity index 82% rename from src/Domains/McpServer/Events/McpInstructionDeletingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionDeletingEvent.php index acdef46..f10972d 100644 --- a/src/Domains/McpServer/Events/McpInstructionDeletingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionDeletingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionReplicatingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionReplicatingEvent.php similarity index 82% rename from src/Domains/McpServer/Events/McpInstructionReplicatingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionReplicatingEvent.php index 65c47e4..cb1f9cb 100644 --- a/src/Domains/McpServer/Events/McpInstructionReplicatingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionReplicatingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionRetrievedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionRetrievedEvent.php similarity index 82% rename from src/Domains/McpServer/Events/McpInstructionRetrievedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionRetrievedEvent.php index 916199f..dbc8720 100644 --- a/src/Domains/McpServer/Events/McpInstructionRetrievedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionRetrievedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionSavedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionSavedEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionSavedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionSavedEvent.php index bcc9918..411fd3a 100644 --- a/src/Domains/McpServer/Events/McpInstructionSavedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionSavedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionSavingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionSavingEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionSavingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionSavingEvent.php index dbc9187..7b7e7ef 100644 --- a/src/Domains/McpServer/Events/McpInstructionSavingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionSavingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionShowingActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionShowingActionEvent.php similarity index 87% rename from src/Domains/McpServer/Events/McpInstructionShowingActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionShowingActionEvent.php index 9d57b8e..398d05c 100644 --- a/src/Domains/McpServer/Events/McpInstructionShowingActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionShowingActionEvent.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; diff --git a/src/Domains/McpServer/Events/McpInstructionShownActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionShownActionEvent.php similarity index 77% rename from src/Domains/McpServer/Events/McpInstructionShownActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionShownActionEvent.php index 0dbfda5..b7a909a 100644 --- a/src/Domains/McpServer/Events/McpInstructionShownActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionShownActionEvent.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ActionFinishedEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionUpdatedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionUpdatedEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionUpdatedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionUpdatedEvent.php index f5b7e34..b54b69b 100644 --- a/src/Domains/McpServer/Events/McpInstructionUpdatedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionUpdatedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionUpdatingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionUpdatingEvent.php similarity index 82% rename from src/Domains/McpServer/Events/McpInstructionUpdatingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionUpdatingEvent.php index 57c6bf6..1f720f7 100644 --- a/src/Domains/McpServer/Events/McpInstructionUpdatingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionUpdatingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionCreatedActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionCreatedActionEvent.php similarity index 78% rename from src/Domains/McpServer/Events/McpInstructionVersionCreatedActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionCreatedActionEvent.php index 0b65bc1..abf5858 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionCreatedActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionCreatedActionEvent.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ActionFinishedEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionCreatedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionCreatedEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionCreatedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionCreatedEvent.php index 9fec391..1a94708 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionCreatedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionCreatedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionCreatingActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionCreatingActionEvent.php similarity index 78% rename from src/Domains/McpServer/Events/McpInstructionVersionCreatingActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionCreatingActionEvent.php index 7167fb0..7a5be4e 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionCreatingActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionCreatingActionEvent.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; use RefactorCircus\Keystone\Contracts\ActionStartingEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionCreatingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionCreatingEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionCreatingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionCreatingEvent.php index 45cee72..bc1d5c9 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionCreatingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionCreatingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionDeletedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionDeletedEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionDeletedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionDeletedEvent.php index e4cfe58..d6708c8 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionDeletedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionDeletedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionDeletingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionDeletingEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionDeletingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionDeletingEvent.php index 5140965..0b875d2 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionDeletingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionDeletingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionPublishedActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionPublishedActionEvent.php similarity index 79% rename from src/Domains/McpServer/Events/McpInstructionVersionPublishedActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionPublishedActionEvent.php index 55a6d56..fb5da09 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionPublishedActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionPublishedActionEvent.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ActionFinishedEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionPublishingActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionPublishingActionEvent.php similarity index 79% rename from src/Domains/McpServer/Events/McpInstructionVersionPublishingActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionPublishingActionEvent.php index e50660b..87c02bc 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionPublishingActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionPublishingActionEvent.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ActionStartingEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionReplicatingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionReplicatingEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionReplicatingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionReplicatingEvent.php index c44a0b6..ddb6b46 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionReplicatingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionReplicatingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionRetrievedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionRetrievedEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionRetrievedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionRetrievedEvent.php index 5a3fa96..c45e4ec 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionRetrievedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionRetrievedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionSavedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionSavedEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionSavedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionSavedEvent.php index 277de5d..6aa2c3d 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionSavedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionSavedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionSavingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionSavingEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionSavingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionSavingEvent.php index 82a71ce..89c3d74 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionSavingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionSavingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionUpdatedEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionUpdatedEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionUpdatedEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionUpdatedEvent.php index c35be86..d867aac 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionUpdatedEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionUpdatedEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionUpdatingEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionUpdatingEvent.php similarity index 81% rename from src/Domains/McpServer/Events/McpInstructionVersionUpdatingEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionUpdatingEvent.php index d6f768a..a7f2d9c 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionUpdatingEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionUpdatingEvent.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ModelLifecycleEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionsListedActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionsListedActionEvent.php similarity index 74% rename from src/Domains/McpServer/Events/McpInstructionVersionsListedActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionsListedActionEvent.php index 5d5797d..ddacc98 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionsListedActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionsListedActionEvent.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Database\Eloquent\Collection; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Contracts\ActionFinishedEvent; /** diff --git a/src/Domains/McpServer/Events/McpInstructionVersionsListingActionEvent.php b/src/Domains/ConcreteServer/Events/McpInstructionVersionsListingActionEvent.php similarity index 78% rename from src/Domains/McpServer/Events/McpInstructionVersionsListingActionEvent.php rename to src/Domains/ConcreteServer/Events/McpInstructionVersionsListingActionEvent.php index fd8d963..9545a1b 100644 --- a/src/Domains/McpServer/Events/McpInstructionVersionsListingActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpInstructionVersionsListingActionEvent.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Contracts\ActionStartingEvent; /** diff --git a/src/Domains/McpServer/Events/McpServersListedActionEvent.php b/src/Domains/ConcreteServer/Events/McpServersListedActionEvent.php similarity index 88% rename from src/Domains/McpServer/Events/McpServersListedActionEvent.php rename to src/Domains/ConcreteServer/Events/McpServersListedActionEvent.php index ff225fa..ae6c764 100644 --- a/src/Domains/McpServer/Events/McpServersListedActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpServersListedActionEvent.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; diff --git a/src/Domains/McpServer/Events/McpServersListingActionEvent.php b/src/Domains/ConcreteServer/Events/McpServersListingActionEvent.php similarity index 85% rename from src/Domains/McpServer/Events/McpServersListingActionEvent.php rename to src/Domains/ConcreteServer/Events/McpServersListingActionEvent.php index 95f4ea6..25b66e8 100644 --- a/src/Domains/McpServer/Events/McpServersListingActionEvent.php +++ b/src/Domains/ConcreteServer/Events/McpServersListingActionEvent.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Events; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; diff --git a/src/Domains/McpServer/Exceptions/McpServerNotFoundException.php b/src/Domains/ConcreteServer/Exceptions/McpServerNotFoundException.php similarity index 80% rename from src/Domains/McpServer/Exceptions/McpServerNotFoundException.php rename to src/Domains/ConcreteServer/Exceptions/McpServerNotFoundException.php index 34d30e3..b1a5de2 100644 --- a/src/Domains/McpServer/Exceptions/McpServerNotFoundException.php +++ b/src/Domains/ConcreteServer/Exceptions/McpServerNotFoundException.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Exceptions; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Exceptions; use InvalidArgumentException; diff --git a/src/Domains/McpServer/Http/Controllers/McpInstructionController.php b/src/Domains/ConcreteServer/Http/Controllers/McpInstructionController.php similarity index 61% rename from src/Domains/McpServer/Http/Controllers/McpInstructionController.php rename to src/Domains/ConcreteServer/Http/Controllers/McpInstructionController.php index 997b4dc..d21d837 100644 --- a/src/Domains/McpServer/Http/Controllers/McpInstructionController.php +++ b/src/Domains/ConcreteServer/Http/Controllers/McpInstructionController.php @@ -2,15 +2,15 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Controllers; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Response; -use RefactorCircus\Cortex\Domains\McpServer\Http\Requests\DeleteMcpInstructionRequest; -use RefactorCircus\Cortex\Domains\McpServer\Http\Requests\IndexMcpInstructionVersionsRequest; -use RefactorCircus\Cortex\Domains\McpServer\Http\Requests\PublishMcpInstructionVersionRequest; -use RefactorCircus\Cortex\Domains\McpServer\Http\Requests\ShowMcpInstructionRequest; -use RefactorCircus\Cortex\Domains\McpServer\Http\Requests\StoreMcpInstructionVersionRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests\DeleteMcpInstructionRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests\IndexMcpInstructionVersionsRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests\PublishMcpInstructionVersionRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests\ShowMcpInstructionRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests\StoreMcpInstructionVersionRequest; final class McpInstructionController { diff --git a/src/Domains/McpServer/Http/Controllers/McpServerController.php b/src/Domains/ConcreteServer/Http/Controllers/McpServerController.php similarity index 58% rename from src/Domains/McpServer/Http/Controllers/McpServerController.php rename to src/Domains/ConcreteServer/Http/Controllers/McpServerController.php index 7017c43..53a7454 100644 --- a/src/Domains/McpServer/Http/Controllers/McpServerController.php +++ b/src/Domains/ConcreteServer/Http/Controllers/McpServerController.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Controllers; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Controllers; use Illuminate\Http\JsonResponse; -use RefactorCircus\Cortex\Domains\McpServer\Http\Requests\IndexMcpServersRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests\IndexMcpServersRequest; final class McpServerController { diff --git a/src/Domains/McpServer/Http/Requests/DeleteMcpInstructionRequest.php b/src/Domains/ConcreteServer/Http/Requests/DeleteMcpInstructionRequest.php similarity index 73% rename from src/Domains/McpServer/Http/Requests/DeleteMcpInstructionRequest.php rename to src/Domains/ConcreteServer/Http/Requests/DeleteMcpInstructionRequest.php index a52bb43..519b0ba 100644 --- a/src/Domains/McpServer/Http/Requests/DeleteMcpInstructionRequest.php +++ b/src/Domains/ConcreteServer/Http/Requests/DeleteMcpInstructionRequest.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests; use Illuminate\Http\Response; -use RefactorCircus\Cortex\Domains\McpServer\Actions\DeleteMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\DeleteMcpInstructionAction; final class DeleteMcpInstructionRequest extends McpInstructionRequest { diff --git a/src/Domains/McpServer/Http/Requests/IndexMcpInstructionVersionsRequest.php b/src/Domains/ConcreteServer/Http/Requests/IndexMcpInstructionVersionsRequest.php similarity index 61% rename from src/Domains/McpServer/Http/Requests/IndexMcpInstructionVersionsRequest.php rename to src/Domains/ConcreteServer/Http/Requests/IndexMcpInstructionVersionsRequest.php index 9fd73d6..f12ed6d 100644 --- a/src/Domains/McpServer/Http/Requests/IndexMcpInstructionVersionsRequest.php +++ b/src/Domains/ConcreteServer/Http/Requests/IndexMcpInstructionVersionsRequest.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests; use Illuminate\Http\JsonResponse; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ListMcpInstructionVersionsAction; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionVersionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ListMcpInstructionVersionsAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionVersionResource; final class IndexMcpInstructionVersionsRequest extends McpInstructionRequest { diff --git a/src/Domains/McpServer/Http/Requests/IndexMcpServersRequest.php b/src/Domains/ConcreteServer/Http/Requests/IndexMcpServersRequest.php similarity index 60% rename from src/Domains/McpServer/Http/Requests/IndexMcpServersRequest.php rename to src/Domains/ConcreteServer/Http/Requests/IndexMcpServersRequest.php index 611804f..e1495c3 100644 --- a/src/Domains/McpServer/Http/Requests/IndexMcpServersRequest.php +++ b/src/Domains/ConcreteServer/Http/Requests/IndexMcpServersRequest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests; use Illuminate\Http\JsonResponse; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ListMcpServersAction; -use RefactorCircus\Cortex\Domains\McpServer\Http\Resources\McpServerResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ListMcpServersAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Resources\McpServerResource; use RefactorCircus\Cortex\Http\Request; final class IndexMcpServersRequest extends Request diff --git a/src/Domains/McpServer/Http/Requests/McpInstructionRequest.php b/src/Domains/ConcreteServer/Http/Requests/McpInstructionRequest.php similarity index 82% rename from src/Domains/McpServer/Http/Requests/McpInstructionRequest.php rename to src/Domains/ConcreteServer/Http/Requests/McpInstructionRequest.php index 941d7ef..e8ee31b 100644 --- a/src/Domains/McpServer/Http/Requests/McpInstructionRequest.php +++ b/src/Domains/ConcreteServer/Http/Requests/McpInstructionRequest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Http\Request; abstract class McpInstructionRequest extends Request diff --git a/src/Domains/McpServer/Http/Requests/PublishMcpInstructionVersionRequest.php b/src/Domains/ConcreteServer/Http/Requests/PublishMcpInstructionVersionRequest.php similarity index 69% rename from src/Domains/McpServer/Http/Requests/PublishMcpInstructionVersionRequest.php rename to src/Domains/ConcreteServer/Http/Requests/PublishMcpInstructionVersionRequest.php index 94b7d3e..7caffa6 100644 --- a/src/Domains/McpServer/Http/Requests/PublishMcpInstructionVersionRequest.php +++ b/src/Domains/ConcreteServer/Http/Requests/PublishMcpInstructionVersionRequest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests; use Illuminate\Http\JsonResponse; -use RefactorCircus\Cortex\Domains\McpServer\Actions\PublishMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\PublishMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionResource; final class PublishMcpInstructionVersionRequest extends McpInstructionRequest { diff --git a/src/Domains/McpServer/Http/Requests/ShowMcpInstructionRequest.php b/src/Domains/ConcreteServer/Http/Requests/ShowMcpInstructionRequest.php similarity index 66% rename from src/Domains/McpServer/Http/Requests/ShowMcpInstructionRequest.php rename to src/Domains/ConcreteServer/Http/Requests/ShowMcpInstructionRequest.php index 21c38c3..707138d 100644 --- a/src/Domains/McpServer/Http/Requests/ShowMcpInstructionRequest.php +++ b/src/Domains/ConcreteServer/Http/Requests/ShowMcpInstructionRequest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests; use Illuminate\Http\JsonResponse; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ShowMcpInstructionAction; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ShowMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionResource; final class ShowMcpInstructionRequest extends McpInstructionRequest { diff --git a/src/Domains/McpServer/Http/Requests/StoreMcpInstructionVersionRequest.php b/src/Domains/ConcreteServer/Http/Requests/StoreMcpInstructionVersionRequest.php similarity index 63% rename from src/Domains/McpServer/Http/Requests/StoreMcpInstructionVersionRequest.php rename to src/Domains/ConcreteServer/Http/Requests/StoreMcpInstructionVersionRequest.php index 9649c9c..0cb5278 100644 --- a/src/Domains/McpServer/Http/Requests/StoreMcpInstructionVersionRequest.php +++ b/src/Domains/ConcreteServer/Http/Requests/StoreMcpInstructionVersionRequest.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests; use Illuminate\Http\JsonResponse; -use RefactorCircus\Cortex\Domains\McpServer\Actions\CreateMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Data\CreateMcpInstructionVersionData; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionVersionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\CreateMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionVersionResource; final class StoreMcpInstructionVersionRequest extends McpInstructionRequest { diff --git a/src/Domains/McpServer/Http/Resources/McpServerResource.php b/src/Domains/ConcreteServer/Http/Resources/McpServerResource.php similarity index 92% rename from src/Domains/McpServer/Http/Resources/McpServerResource.php rename to src/Domains/ConcreteServer/Http/Resources/McpServerResource.php index 91fae33..703f98c 100644 --- a/src/Domains/McpServer/Http/Resources/McpServerResource.php +++ b/src/Domains/ConcreteServer/Http/Resources/McpServerResource.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Http\Resources; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Resources; use Illuminate\Contracts\JsonSchema\JsonSchema; use Illuminate\Http\Request; diff --git a/src/Domains/McpServer/Mcp/Requests/CreateServerInstructionVersionMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/CreateServerInstructionVersionMcpRequest.php similarity index 65% rename from src/Domains/McpServer/Mcp/Requests/CreateServerInstructionVersionMcpRequest.php rename to src/Domains/ConcreteServer/Mcp/Requests/CreateServerInstructionVersionMcpRequest.php index 9ac86b1..88c0356 100644 --- a/src/Domains/McpServer/Mcp/Requests/CreateServerInstructionVersionMcpRequest.php +++ b/src/Domains/ConcreteServer/Mcp/Requests/CreateServerInstructionVersionMcpRequest.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests; use Laravel\Mcp\ResponseFactory; -use RefactorCircus\Cortex\Domains\McpServer\Actions\CreateMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Data\CreateMcpInstructionVersionData; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionVersionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\CreateMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionVersionResource; final class CreateServerInstructionVersionMcpRequest extends ServerMcpRequest { diff --git a/src/Domains/McpServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php similarity index 78% rename from src/Domains/McpServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php rename to src/Domains/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php index 6a7d866..95213b3 100644 --- a/src/Domains/McpServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php +++ b/src/Domains/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests; use Laravel\Mcp\Response; -use RefactorCircus\Cortex\Domains\McpServer\Actions\DeleteMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\DeleteMcpInstructionAction; final class DeleteServerInstructionsMcpRequest extends ServerMcpRequest { diff --git a/src/Domains/McpServer/Mcp/Requests/ListServerInstructionVersionsMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/ListServerInstructionVersionsMcpRequest.php similarity index 66% rename from src/Domains/McpServer/Mcp/Requests/ListServerInstructionVersionsMcpRequest.php rename to src/Domains/ConcreteServer/Mcp/Requests/ListServerInstructionVersionsMcpRequest.php index 14353a0..88f2a38 100644 --- a/src/Domains/McpServer/Mcp/Requests/ListServerInstructionVersionsMcpRequest.php +++ b/src/Domains/ConcreteServer/Mcp/Requests/ListServerInstructionVersionsMcpRequest.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests; use Laravel\Mcp\ResponseFactory; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ListMcpInstructionVersionsAction; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionVersionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ListMcpInstructionVersionsAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionVersionResource; final class ListServerInstructionVersionsMcpRequest extends ServerMcpRequest { diff --git a/src/Domains/McpServer/Mcp/Requests/ListServersMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/ListServersMcpRequest.php similarity index 62% rename from src/Domains/McpServer/Mcp/Requests/ListServersMcpRequest.php rename to src/Domains/ConcreteServer/Mcp/Requests/ListServersMcpRequest.php index c9a8196..b21baec 100644 --- a/src/Domains/McpServer/Mcp/Requests/ListServersMcpRequest.php +++ b/src/Domains/ConcreteServer/Mcp/Requests/ListServersMcpRequest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests; use Laravel\Mcp\ResponseFactory; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ListMcpServersAction; -use RefactorCircus\Cortex\Domains\McpServer\Http\Resources\McpServerResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ListMcpServersAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Resources\McpServerResource; use RefactorCircus\Cortex\Mcp\Request; final class ListServersMcpRequest extends Request diff --git a/src/Domains/McpServer/Mcp/Requests/PublishServerInstructionVersionMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/PublishServerInstructionVersionMcpRequest.php similarity index 73% rename from src/Domains/McpServer/Mcp/Requests/PublishServerInstructionVersionMcpRequest.php rename to src/Domains/ConcreteServer/Mcp/Requests/PublishServerInstructionVersionMcpRequest.php index a892ade..b368c38 100644 --- a/src/Domains/McpServer/Mcp/Requests/PublishServerInstructionVersionMcpRequest.php +++ b/src/Domains/ConcreteServer/Mcp/Requests/PublishServerInstructionVersionMcpRequest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests; use Laravel\Mcp\ResponseFactory; -use RefactorCircus\Cortex\Domains\McpServer\Actions\PublishMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\PublishMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionResource; final class PublishServerInstructionVersionMcpRequest extends ServerMcpRequest { diff --git a/src/Domains/McpServer/Mcp/Requests/ServerMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/ServerMcpRequest.php similarity index 87% rename from src/Domains/McpServer/Mcp/Requests/ServerMcpRequest.php rename to src/Domains/ConcreteServer/Mcp/Requests/ServerMcpRequest.php index 7eca4e5..68dfa28 100644 --- a/src/Domains/McpServer/Mcp/Requests/ServerMcpRequest.php +++ b/src/Domains/ConcreteServer/Mcp/Requests/ServerMcpRequest.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests; use Illuminate\Database\Eloquent\ModelNotFoundException; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Mcp\Request; abstract class ServerMcpRequest extends Request diff --git a/src/Domains/McpServer/Mcp/Requests/ShowServerInstructionsMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/ShowServerInstructionsMcpRequest.php similarity index 71% rename from src/Domains/McpServer/Mcp/Requests/ShowServerInstructionsMcpRequest.php rename to src/Domains/ConcreteServer/Mcp/Requests/ShowServerInstructionsMcpRequest.php index f5adcd4..d28a7d6 100644 --- a/src/Domains/McpServer/Mcp/Requests/ShowServerInstructionsMcpRequest.php +++ b/src/Domains/ConcreteServer/Mcp/Requests/ShowServerInstructionsMcpRequest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests; use Laravel\Mcp\ResponseFactory; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ShowMcpInstructionAction; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ShowMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionResource; final class ShowServerInstructionsMcpRequest extends ServerMcpRequest { diff --git a/src/Domains/McpServer/Mcp/Tools/CreateServerInstructionVersionTool.php b/src/Domains/ConcreteServer/Mcp/Tools/CreateServerInstructionVersionTool.php similarity index 81% rename from src/Domains/McpServer/Mcp/Tools/CreateServerInstructionVersionTool.php rename to src/Domains/ConcreteServer/Mcp/Tools/CreateServerInstructionVersionTool.php index 554b91e..f50208a 100644 --- a/src/Domains/McpServer/Mcp/Tools/CreateServerInstructionVersionTool.php +++ b/src/Domains/ConcreteServer/Mcp/Tools/CreateServerInstructionVersionTool.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools; use Illuminate\Contracts\JsonSchema\JsonSchema; use Laravel\Mcp\Response; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Attributes\Description; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests\CreateServerInstructionVersionMcpRequest; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionVersionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests\CreateServerInstructionVersionMcpRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionVersionResource; use RefactorCircus\Keystone\Mcp\Tool; #[Description('Create a new immutable instruction version for a registered MCP server. Not published unless requested.')] diff --git a/src/Domains/McpServer/Mcp/Tools/DeleteServerInstructionsTool.php b/src/Domains/ConcreteServer/Mcp/Tools/DeleteServerInstructionsTool.php similarity index 82% rename from src/Domains/McpServer/Mcp/Tools/DeleteServerInstructionsTool.php rename to src/Domains/ConcreteServer/Mcp/Tools/DeleteServerInstructionsTool.php index 7e335c4..779593b 100644 --- a/src/Domains/McpServer/Mcp/Tools/DeleteServerInstructionsTool.php +++ b/src/Domains/ConcreteServer/Mcp/Tools/DeleteServerInstructionsTool.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools; use Illuminate\Contracts\JsonSchema\JsonSchema; use Laravel\Mcp\Response; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Attributes\Description; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests\DeleteServerInstructionsMcpRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests\DeleteServerInstructionsMcpRequest; use RefactorCircus\Keystone\Mcp\Tool; #[Description('Remove the instruction override and its version history for a registered MCP server; the code-declared instructions take over.')] diff --git a/src/Domains/McpServer/Mcp/Tools/ListServerInstructionVersionsTool.php b/src/Domains/ConcreteServer/Mcp/Tools/ListServerInstructionVersionsTool.php similarity index 78% rename from src/Domains/McpServer/Mcp/Tools/ListServerInstructionVersionsTool.php rename to src/Domains/ConcreteServer/Mcp/Tools/ListServerInstructionVersionsTool.php index 003fb5a..da1f8ad 100644 --- a/src/Domains/McpServer/Mcp/Tools/ListServerInstructionVersionsTool.php +++ b/src/Domains/ConcreteServer/Mcp/Tools/ListServerInstructionVersionsTool.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools; use Illuminate\Contracts\JsonSchema\JsonSchema; use Laravel\Mcp\Response; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Attributes\Description; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests\ListServerInstructionVersionsMcpRequest; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionVersionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests\ListServerInstructionVersionsMcpRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionVersionResource; use RefactorCircus\Keystone\Mcp\Tool; #[Description('List the instruction versions of a registered MCP server, newest first.')] diff --git a/src/Domains/McpServer/Mcp/Tools/ListServersTool.php b/src/Domains/ConcreteServer/Mcp/Tools/ListServersTool.php similarity index 77% rename from src/Domains/McpServer/Mcp/Tools/ListServersTool.php rename to src/Domains/ConcreteServer/Mcp/Tools/ListServersTool.php index 36a2b11..f0bc6a0 100644 --- a/src/Domains/McpServer/Mcp/Tools/ListServersTool.php +++ b/src/Domains/ConcreteServer/Mcp/Tools/ListServersTool.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools; use Illuminate\Contracts\JsonSchema\JsonSchema; use Laravel\Mcp\Response; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Attributes\Description; -use RefactorCircus\Cortex\Domains\McpServer\Http\Resources\McpServerResource; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests\ListServersMcpRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Resources\McpServerResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests\ListServersMcpRequest; use RefactorCircus\Keystone\Mcp\Tool; #[Description('List the MCP servers registered with Cortex, including the instructions each currently serves.')] diff --git a/src/Domains/McpServer/Mcp/Tools/PublishServerInstructionVersionTool.php b/src/Domains/ConcreteServer/Mcp/Tools/PublishServerInstructionVersionTool.php similarity index 80% rename from src/Domains/McpServer/Mcp/Tools/PublishServerInstructionVersionTool.php rename to src/Domains/ConcreteServer/Mcp/Tools/PublishServerInstructionVersionTool.php index 1152d74..0b548e6 100644 --- a/src/Domains/McpServer/Mcp/Tools/PublishServerInstructionVersionTool.php +++ b/src/Domains/ConcreteServer/Mcp/Tools/PublishServerInstructionVersionTool.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools; use Illuminate\Contracts\JsonSchema\JsonSchema; use Laravel\Mcp\Response; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Attributes\Description; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests\PublishServerInstructionVersionMcpRequest; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests\PublishServerInstructionVersionMcpRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionResource; use RefactorCircus\Keystone\Mcp\Tool; #[Description('Publish a specific instruction version of a registered MCP server, replacing its code-declared instructions.')] diff --git a/src/Domains/McpServer/Mcp/Tools/ShowServerInstructionsTool.php b/src/Domains/ConcreteServer/Mcp/Tools/ShowServerInstructionsTool.php similarity index 78% rename from src/Domains/McpServer/Mcp/Tools/ShowServerInstructionsTool.php rename to src/Domains/ConcreteServer/Mcp/Tools/ShowServerInstructionsTool.php index 342282a..4ef0194 100644 --- a/src/Domains/McpServer/Mcp/Tools/ShowServerInstructionsTool.php +++ b/src/Domains/ConcreteServer/Mcp/Tools/ShowServerInstructionsTool.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools; use Illuminate\Contracts\JsonSchema\JsonSchema; use Laravel\Mcp\Response; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Attributes\Description; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Requests\ShowServerInstructionsMcpRequest; -use RefactorCircus\Cortex\Domains\McpServer\Resources\McpInstructionResource; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests\ShowServerInstructionsMcpRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionResource; use RefactorCircus\Keystone\Mcp\Tool; #[Description('Show the instruction override for a registered MCP server, including its published version.')] diff --git a/src/Domains/McpServer/Models/McpInstructionModel.php b/src/Domains/ConcreteServer/Models/McpInstructionModel.php similarity index 96% rename from src/Domains/McpServer/Models/McpInstructionModel.php rename to src/Domains/ConcreteServer/Models/McpInstructionModel.php index 0dee3a4..b020edf 100644 --- a/src/Domains/McpServer/Models/McpInstructionModel.php +++ b/src/Domains/ConcreteServer/Models/McpInstructionModel.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Models; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Models; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Eloquent\Factories\HasFactory; diff --git a/src/Domains/McpServer/Models/McpInstructionVersionModel.php b/src/Domains/ConcreteServer/Models/McpInstructionVersionModel.php similarity index 96% rename from src/Domains/McpServer/Models/McpInstructionVersionModel.php rename to src/Domains/ConcreteServer/Models/McpInstructionVersionModel.php index 0179dfa..fac7f26 100644 --- a/src/Domains/McpServer/Models/McpInstructionVersionModel.php +++ b/src/Domains/ConcreteServer/Models/McpInstructionVersionModel.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Models; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Models; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Eloquent\Factories\HasFactory; diff --git a/src/Domains/McpServer/Policies/McpInstructionPolicy.php b/src/Domains/ConcreteServer/Policies/McpInstructionPolicy.php similarity index 87% rename from src/Domains/McpServer/Policies/McpInstructionPolicy.php rename to src/Domains/ConcreteServer/Policies/McpInstructionPolicy.php index b32828f..6f37646 100644 --- a/src/Domains/McpServer/Policies/McpInstructionPolicy.php +++ b/src/Domains/ConcreteServer/Policies/McpInstructionPolicy.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Policies; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Policies; use Illuminate\Contracts\Auth\Authenticatable; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Cortex\Support\Policies\Policy; /** diff --git a/src/Domains/McpServer/Policies/McpInstructionVersionPolicy.php b/src/Domains/ConcreteServer/Policies/McpInstructionVersionPolicy.php similarity index 83% rename from src/Domains/McpServer/Policies/McpInstructionVersionPolicy.php rename to src/Domains/ConcreteServer/Policies/McpInstructionVersionPolicy.php index d81ee7b..d041753 100644 --- a/src/Domains/McpServer/Policies/McpInstructionVersionPolicy.php +++ b/src/Domains/ConcreteServer/Policies/McpInstructionVersionPolicy.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Policies; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Policies; use Illuminate\Contracts\Auth\Authenticatable; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Cortex\Support\Policies\Policy; /** diff --git a/src/Domains/McpServer/Resources/McpInstructionResource.php b/src/Domains/ConcreteServer/Resources/McpInstructionResource.php similarity index 89% rename from src/Domains/McpServer/Resources/McpInstructionResource.php rename to src/Domains/ConcreteServer/Resources/McpInstructionResource.php index 500c993..2ad29d0 100644 --- a/src/Domains/McpServer/Resources/McpInstructionResource.php +++ b/src/Domains/ConcreteServer/Resources/McpInstructionResource.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Resources; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Resources; use Illuminate\Contracts\JsonSchema\JsonSchema; use Illuminate\Http\Request; use Illuminate\JsonSchema\Types\Type; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Keystone\Http\Resources\JsonResource; /** diff --git a/src/Domains/McpServer/Resources/McpInstructionVersionResource.php b/src/Domains/ConcreteServer/Resources/McpInstructionVersionResource.php similarity index 86% rename from src/Domains/McpServer/Resources/McpInstructionVersionResource.php rename to src/Domains/ConcreteServer/Resources/McpInstructionVersionResource.php index bbf99ce..893c32f 100644 --- a/src/Domains/McpServer/Resources/McpInstructionVersionResource.php +++ b/src/Domains/ConcreteServer/Resources/McpInstructionVersionResource.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Resources; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Resources; use Illuminate\Contracts\JsonSchema\JsonSchema; use Illuminate\Http\Request; use Illuminate\JsonSchema\Types\Type; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Keystone\Http\Resources\JsonResource; /** diff --git a/src/Domains/McpServer/Services/McpInstructionOverrides.php b/src/Domains/ConcreteServer/Services/McpInstructionOverrides.php similarity index 90% rename from src/Domains/McpServer/Services/McpInstructionOverrides.php rename to src/Domains/ConcreteServer/Services/McpInstructionOverrides.php index 15546d5..66ec079 100644 --- a/src/Domains/McpServer/Services/McpInstructionOverrides.php +++ b/src/Domains/ConcreteServer/Services/McpInstructionOverrides.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Services; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Services; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Cortex\Support\PublicationCache; /** diff --git a/src/Domains/McpServer/Services/McpServerRegistry.php b/src/Domains/ConcreteServer/Services/McpServerRegistry.php similarity index 96% rename from src/Domains/McpServer/Services/McpServerRegistry.php rename to src/Domains/ConcreteServer/Services/McpServerRegistry.php index bfce432..4747a43 100644 --- a/src/Domains/McpServer/Services/McpServerRegistry.php +++ b/src/Domains/ConcreteServer/Services/McpServerRegistry.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Services; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Services; use Illuminate\Contracts\Container\Container; use Illuminate\Support\Str; @@ -10,7 +10,7 @@ use Laravel\Mcp\Server as McpServer; use Laravel\Mcp\Server\Attributes\Instructions; use Laravel\Mcp\Server\Attributes\Name; -use RefactorCircus\Cortex\Domains\McpServer\Exceptions\McpServerNotFoundException; +use RefactorCircus\Cortex\Domains\ConcreteServer\Exceptions\McpServerNotFoundException; use RefactorCircus\Cortex\Mcp\CortexServer; use ReflectionClass; diff --git a/src/Domains/McpServer/Support/Server.php b/src/Domains/ConcreteServer/Support/Server.php similarity index 77% rename from src/Domains/McpServer/Support/Server.php rename to src/Domains/ConcreteServer/Support/Server.php index 81d260f..38c1015 100644 --- a/src/Domains/McpServer/Support/Server.php +++ b/src/Domains/ConcreteServer/Support/Server.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace RefactorCircus\Cortex\Domains\McpServer\Support; +namespace RefactorCircus\Cortex\Domains\ConcreteServer\Support; use Laravel\Mcp\Server as McpServer; -use RefactorCircus\Cortex\Domains\McpServer\Concerns\HasVersionedInstructions; +use RefactorCircus\Cortex\Domains\ConcreteServer\Concerns\HasVersionedInstructions; /** * Base class for MCP servers whose instructions Cortex manages: register the diff --git a/src/Domains/McpServer/routes.php b/src/Domains/ConcreteServer/routes.php similarity index 83% rename from src/Domains/McpServer/routes.php rename to src/Domains/ConcreteServer/routes.php index 360e5a6..826b356 100644 --- a/src/Domains/McpServer/routes.php +++ b/src/Domains/ConcreteServer/routes.php @@ -3,8 +3,8 @@ declare(strict_types=1); use Illuminate\Support\Facades\Route; -use RefactorCircus\Cortex\Domains\McpServer\Http\Controllers\McpInstructionController; -use RefactorCircus\Cortex\Domains\McpServer\Http\Controllers\McpServerController; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Controllers\McpInstructionController; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Controllers\McpServerController; Route::get('servers', [McpServerController::class, 'index'])->name('servers.index'); diff --git a/src/Domains/DomainServiceProvider.php b/src/Domains/DomainServiceProvider.php index a65b6a7..3620b45 100644 --- a/src/Domains/DomainServiceProvider.php +++ b/src/Domains/DomainServiceProvider.php @@ -6,7 +6,7 @@ use Illuminate\Support\ServiceProvider; use RefactorCircus\Cortex\Domains\ConcreteAgent\ConcreteAgentServiceProvider; -use RefactorCircus\Cortex\Domains\McpServer\McpServerServiceProvider; +use RefactorCircus\Cortex\Domains\ConcreteServer\ConcreteServerServiceProvider; use RefactorCircus\Cortex\Domains\RedirectDomain\RedirectDomainServiceProvider; use RefactorCircus\Cortex\Domains\Tool\ToolServiceProvider; use RefactorCircus\Cortex\Domains\VirtualAgent\VirtualAgentServiceProvider; @@ -20,7 +20,7 @@ class DomainServiceProvider extends ServiceProvider */ private array $providers = [ ConcreteAgentServiceProvider::class, - McpServerServiceProvider::class, + ConcreteServerServiceProvider::class, RedirectDomainServiceProvider::class, ToolServiceProvider::class, VirtualAgentServiceProvider::class, diff --git a/src/Facades/Cortex.php b/src/Facades/Cortex.php index 2eba947..b290b03 100644 --- a/src/Facades/Cortex.php +++ b/src/Facades/Cortex.php @@ -8,7 +8,7 @@ /** * @method static \RefactorCircus\Cortex\Domains\Tool\Services\ToolRegistry tools() - * @method static \RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry servers() + * @method static \RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry servers() * @method static \RefactorCircus\Cortex\Domains\ConcreteAgent\Services\AgentRegistry agents() * @method static \RefactorCircus\Cortex\Domains\VirtualAgent\Support\DbAgent virtualAgent(string $slug) * @method static \Laravel\Ai\Contracts\Agent concreteAgent(string $name) diff --git a/src/Mcp/CortexServer.php b/src/Mcp/CortexServer.php index c05c8a6..c8fb657 100644 --- a/src/Mcp/CortexServer.php +++ b/src/Mcp/CortexServer.php @@ -17,12 +17,12 @@ use RefactorCircus\Cortex\Domains\ConcreteAgent\Mcp\Tools\RunConcreteAgentTool; use RefactorCircus\Cortex\Domains\ConcreteAgent\Mcp\Tools\ShowConcreteAgentTool; use RefactorCircus\Cortex\Domains\ConcreteAgent\Mcp\Tools\UpdateConcreteAgentToolsTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\CreateServerInstructionVersionTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\DeleteServerInstructionsTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\ListServerInstructionVersionsTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\ListServersTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\PublishServerInstructionVersionTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\ShowServerInstructionsTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\CreateServerInstructionVersionTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\DeleteServerInstructionsTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ListServerInstructionVersionsTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ListServersTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\PublishServerInstructionVersionTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ShowServerInstructionsTool; use RefactorCircus\Cortex\Domains\RedirectDomain\Mcp\Tools\CreateRedirectDomainTool; use RefactorCircus\Cortex\Domains\RedirectDomain\Mcp\Tools\DeleteRedirectDomainTool; use RefactorCircus\Cortex\Domains\RedirectDomain\Mcp\Tools\ListRedirectDomainsTool; diff --git a/tests/Feature/EventsTest.php b/tests/Feature/EventsTest.php index 01e83dd..eb90721 100644 --- a/tests/Feature/EventsTest.php +++ b/tests/Feature/EventsTest.php @@ -17,13 +17,13 @@ use RefactorCircus\Cortex\Domains\ConcreteAgent\Data\RunConcreteAgentData; use RefactorCircus\Cortex\Domains\ConcreteAgent\Data\UpdateConcreteAgentToolsData; use RefactorCircus\Cortex\Domains\ConcreteAgent\Services\AgentRegistry; -use RefactorCircus\Cortex\Domains\McpServer\Actions\CreateMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Actions\DeleteMcpInstructionAction; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ListMcpInstructionVersionsAction; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ListMcpServersAction; -use RefactorCircus\Cortex\Domains\McpServer\Actions\PublishMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ShowMcpInstructionAction; -use RefactorCircus\Cortex\Domains\McpServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\CreateMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\DeleteMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ListMcpInstructionVersionsAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ListMcpServersAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\PublishMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ShowMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; use RefactorCircus\Cortex\Domains\RedirectDomain\Actions\CreateRedirectDomainAction; use RefactorCircus\Cortex\Domains\RedirectDomain\Actions\DeleteRedirectDomainAction; use RefactorCircus\Cortex\Domains\RedirectDomain\Actions\ListRedirectDomainsAction; diff --git a/tests/Feature/Http/McpInstructionsTest.php b/tests/Feature/Http/McpInstructionsTest.php index db252e2..1b3a30b 100644 --- a/tests/Feature/Http/McpInstructionsTest.php +++ b/tests/Feature/Http/McpInstructionsTest.php @@ -3,9 +3,9 @@ declare(strict_types=1); use Laravel\Mcp\Server\Transport\FakeTransporter; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Tests\Fixtures\EchoServer; beforeEach(function () { diff --git a/tests/Feature/Mcp/ServerInstructionToolsTest.php b/tests/Feature/Mcp/ServerInstructionToolsTest.php index 5b505a1..4fd05c8 100644 --- a/tests/Feature/Mcp/ServerInstructionToolsTest.php +++ b/tests/Feature/Mcp/ServerInstructionToolsTest.php @@ -3,14 +3,14 @@ declare(strict_types=1); use Illuminate\Testing\Fluent\AssertableJson; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\CreateServerInstructionVersionTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\DeleteServerInstructionsTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\ListServerInstructionVersionsTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\ListServersTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\PublishServerInstructionVersionTool; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\ShowServerInstructionsTool; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\CreateServerInstructionVersionTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\DeleteServerInstructionsTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ListServerInstructionVersionsTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ListServersTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\PublishServerInstructionVersionTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ShowServerInstructionsTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Tests\Fixtures\EchoServer; beforeEach(function () { diff --git a/tests/Feature/McpServerRegistryTest.php b/tests/Feature/McpServerRegistryTest.php index ac291db..df35e3f 100644 --- a/tests/Feature/McpServerRegistryTest.php +++ b/tests/Feature/McpServerRegistryTest.php @@ -3,10 +3,12 @@ declare(strict_types=1); use RefactorCircus\Cortex\Cortex; -use RefactorCircus\Cortex\Domains\McpServer\Actions\ListMcpServersAction; -use RefactorCircus\Cortex\Domains\McpServer\Exceptions\McpServerNotFoundException; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ListMcpServersAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\ConcreteServerServiceProvider; +use RefactorCircus\Cortex\Domains\ConcreteServer\Exceptions\McpServerNotFoundException; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\DomainServiceProvider; use RefactorCircus\Cortex\Mcp\CortexServer; use RefactorCircus\Cortex\Support\PublicationCache; use RefactorCircus\Cortex\Tests\Fixtures\EchoServer; @@ -87,6 +89,16 @@ ->and($servers[1]['instructions'])->toBe('Published echo instructions.'); }); +it('registers the ConcreteServer domain from the domain provider', function () { + $domains = (new ReflectionProperty(DomainServiceProvider::class, 'providers')) + ->getValue(app()->getProvider(DomainServiceProvider::class)); + + expect($domains)->toContain(ConcreteServerServiceProvider::class) + ->and(app()->getProvider(ConcreteServerServiceProvider::class))->toBeInstanceOf(ConcreteServerServiceProvider::class) + ->and(is_dir(dirname(__DIR__, 2).'/src/Domains/ConcreteServer'))->toBeTrue() + ->and(is_dir(dirname(__DIR__, 2).'/src/Domains/McpServer'))->toBeFalse(); +}); + it('exposes the registry through the manager and facade', function () { expect(app(Cortex::class)->servers())->toBe(app(McpServerRegistry::class)) ->and(RefactorCircus\Cortex\Facades\Cortex::servers())->toBe(app(McpServerRegistry::class)); diff --git a/tests/Feature/ModelsTest.php b/tests/Feature/ModelsTest.php index 6866b25..f10eae2 100644 --- a/tests/Feature/ModelsTest.php +++ b/tests/Feature/ModelsTest.php @@ -5,8 +5,8 @@ use Illuminate\Database\QueryException; use RefactorCircus\Cortex\Domains\ConcreteAgent\Models\ConcreteAgentOverrideModel; use RefactorCircus\Cortex\Domains\ConcreteAgent\Models\ConcreteAgentOverrideVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Cortex\Domains\Tool\Models\ToolDescriptionModel; use RefactorCircus\Cortex\Domains\Tool\Models\ToolDescriptionVersionModel; use RefactorCircus\Cortex\Domains\VirtualAgent\Models\VirtualAgentModel; diff --git a/tests/Feature/PerformanceTest.php b/tests/Feature/PerformanceTest.php index 11c6330..00d28bc 100644 --- a/tests/Feature/PerformanceTest.php +++ b/tests/Feature/PerformanceTest.php @@ -11,8 +11,8 @@ use RefactorCircus\Cortex\Domains\ConcreteAgent\Actions\CreateConcreteAgentVersionAction; use RefactorCircus\Cortex\Domains\ConcreteAgent\Data\CreateConcreteAgentVersionData; use RefactorCircus\Cortex\Domains\ConcreteAgent\Services\AgentRegistry; -use RefactorCircus\Cortex\Domains\McpServer\Actions\CreateMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\CreateMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; use RefactorCircus\Cortex\Domains\RedirectDomain\Events\RedirectDomainsListingActionEvent; use RefactorCircus\Cortex\Domains\RedirectDomain\Models\RedirectDomainModel; use RefactorCircus\Cortex\Domains\Tool\Actions\CreateToolDescriptionVersionAction; diff --git a/tests/Feature/PolicyTest.php b/tests/Feature/PolicyTest.php index 76f3653..b6cdea9 100644 --- a/tests/Feature/PolicyTest.php +++ b/tests/Feature/PolicyTest.php @@ -9,11 +9,11 @@ use RefactorCircus\Cortex\Domains\ConcreteAgent\Models\ConcreteAgentOverrideVersionModel; use RefactorCircus\Cortex\Domains\ConcreteAgent\Policies\ConcreteAgentOverridePolicy; use RefactorCircus\Cortex\Domains\ConcreteAgent\Policies\ConcreteAgentOverrideVersionPolicy; -use RefactorCircus\Cortex\Domains\McpServer\Mcp\Tools\CreateServerInstructionVersionTool; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel; -use RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionPolicy; -use RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionVersionPolicy; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\CreateServerInstructionVersionTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Policies\McpInstructionPolicy; +use RefactorCircus\Cortex\Domains\ConcreteServer\Policies\McpInstructionVersionPolicy; use RefactorCircus\Cortex\Domains\Tool\Models\ToolDescriptionModel; use RefactorCircus\Cortex\Domains\Tool\Models\ToolDescriptionVersionModel; use RefactorCircus\Cortex\Domains\Tool\Policies\ToolDescriptionPolicy; diff --git a/tests/Feature/PublicationCacheTest.php b/tests/Feature/PublicationCacheTest.php index 107e547..4b9f4ea 100644 --- a/tests/Feature/PublicationCacheTest.php +++ b/tests/Feature/PublicationCacheTest.php @@ -11,12 +11,12 @@ use RefactorCircus\Cortex\Domains\ConcreteAgent\Data\CreateConcreteAgentVersionData; use RefactorCircus\Cortex\Domains\ConcreteAgent\Models\ConcreteAgentOverrideModel; use RefactorCircus\Cortex\Domains\ConcreteAgent\Services\AgentRegistry; -use RefactorCircus\Cortex\Domains\McpServer\Actions\CreateMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Actions\DeleteMcpInstructionAction; -use RefactorCircus\Cortex\Domains\McpServer\Actions\PublishMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Data\CreateMcpInstructionVersionData; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpInstructionOverrides; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\CreateMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\DeleteMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\PublishMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpInstructionOverrides; use RefactorCircus\Cortex\Domains\Tool\Actions\CreateToolDescriptionVersionAction; use RefactorCircus\Cortex\Domains\Tool\Actions\DeleteToolDescriptionAction; use RefactorCircus\Cortex\Domains\Tool\Actions\PublishToolDescriptionVersionAction; diff --git a/tests/Feature/ServerBaseTest.php b/tests/Feature/ServerBaseTest.php index 2aab189..6879751 100644 --- a/tests/Feature/ServerBaseTest.php +++ b/tests/Feature/ServerBaseTest.php @@ -3,8 +3,8 @@ declare(strict_types=1); use Laravel\Mcp\Server\Transport\FakeTransporter; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Mcp\CortexServer; use RefactorCircus\Cortex\Support\PublicationCache; use RefactorCircus\Cortex\Tests\Fixtures\EchoServer; diff --git a/tests/Feature/Ui/ScreenControlsTest.php b/tests/Feature/Ui/ScreenControlsTest.php index c0a01fe..9bb6ea1 100644 --- a/tests/Feature/Ui/ScreenControlsTest.php +++ b/tests/Feature/Ui/ScreenControlsTest.php @@ -13,7 +13,7 @@ use RefactorCircus\Cortex\Atrium\CortexPlugin; use RefactorCircus\Cortex\Domains\ConcreteAgent\Models\ConcreteAgentOverrideModel; use RefactorCircus\Cortex\Domains\ConcreteAgent\Services\AgentRegistry; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Cortex\Domains\Tool\Models\ToolDescriptionModel; use RefactorCircus\Cortex\Domains\VirtualAgent\Models\VirtualAgentModel; use RefactorCircus\Cortex\Domains\VirtualAgent\Support\DbAgent; diff --git a/tests/Fixtures/EchoServer.php b/tests/Fixtures/EchoServer.php index 87693d4..244c91f 100644 --- a/tests/Fixtures/EchoServer.php +++ b/tests/Fixtures/EchoServer.php @@ -6,7 +6,7 @@ use Laravel\Mcp\Server\Attributes\Instructions; use Laravel\Mcp\Server\Attributes\Name; -use RefactorCircus\Cortex\Domains\McpServer\Support\Server; +use RefactorCircus\Cortex\Domains\ConcreteServer\Support\Server; #[Name('Echo Server')] #[Instructions('Code-declared echo server instructions.')] diff --git a/tests/Fixtures/PlainServer.php b/tests/Fixtures/PlainServer.php index 4ca104c..bdcee3a 100644 --- a/tests/Fixtures/PlainServer.php +++ b/tests/Fixtures/PlainServer.php @@ -4,7 +4,7 @@ namespace RefactorCircus\Cortex\Tests\Fixtures; -use RefactorCircus\Cortex\Domains\McpServer\Support\Server; +use RefactorCircus\Cortex\Domains\ConcreteServer\Support\Server; final class PlainServer extends Server { diff --git a/tests/Fixtures/Policies/GrantedMcpInstructionPolicy.php b/tests/Fixtures/Policies/GrantedMcpInstructionPolicy.php index cec3522..ee14303 100644 --- a/tests/Fixtures/Policies/GrantedMcpInstructionPolicy.php +++ b/tests/Fixtures/Policies/GrantedMcpInstructionPolicy.php @@ -5,8 +5,8 @@ namespace RefactorCircus\Cortex\Tests\Fixtures\Policies; use Illuminate\Contracts\Auth\Authenticatable; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionPolicy; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Policies\McpInstructionPolicy; /** * Each ability only for users granted "server-instructions.{ability}". diff --git a/tests/Fixtures/Policies/SignedInMcpInstructionPolicy.php b/tests/Fixtures/Policies/SignedInMcpInstructionPolicy.php index 8fed192..a32d2d5 100644 --- a/tests/Fixtures/Policies/SignedInMcpInstructionPolicy.php +++ b/tests/Fixtures/Policies/SignedInMcpInstructionPolicy.php @@ -5,7 +5,7 @@ namespace RefactorCircus\Cortex\Tests\Fixtures\Policies; use Illuminate\Contracts\Auth\Authenticatable; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; /** * Server instructions are for signed-in users only: the user parameter is not diff --git a/tests/Modes/RenamedTables/RenamedTablesTest.php b/tests/Modes/RenamedTables/RenamedTablesTest.php index 64783d7..f41b14d 100644 --- a/tests/Modes/RenamedTables/RenamedTablesTest.php +++ b/tests/Modes/RenamedTables/RenamedTablesTest.php @@ -5,8 +5,8 @@ use Illuminate\Support\Facades\Schema; use RefactorCircus\Cortex\Domains\ConcreteAgent\Models\ConcreteAgentOverrideModel; use RefactorCircus\Cortex\Domains\ConcreteAgent\Services\AgentRegistry; -use RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel; -use RefactorCircus\Cortex\Domains\McpServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Domains\RedirectDomain\Models\RedirectDomainModel; use RefactorCircus\Cortex\Domains\Tool\Models\ToolDescriptionModel; use RefactorCircus\Cortex\Domains\Tool\Services\ToolRegistry; diff --git a/workbench/app/Mcp/Servers/CatalogServer.php b/workbench/app/Mcp/Servers/CatalogServer.php index 8c2d3ef..05f9080 100644 --- a/workbench/app/Mcp/Servers/CatalogServer.php +++ b/workbench/app/Mcp/Servers/CatalogServer.php @@ -7,7 +7,7 @@ use Laravel\Mcp\Server\Attributes\Instructions; use Laravel\Mcp\Server\Attributes\Name; use Laravel\Mcp\Server\Attributes\Version; -use RefactorCircus\Cortex\Domains\McpServer\Support\Server; +use RefactorCircus\Cortex\Domains\ConcreteServer\Support\Server; use Workbench\App\Domains\Catalog\Tools\CheckInventoryTool; /** diff --git a/workbench/app/Mcp/Servers/SupportServer.php b/workbench/app/Mcp/Servers/SupportServer.php index a061515..b24fb3d 100644 --- a/workbench/app/Mcp/Servers/SupportServer.php +++ b/workbench/app/Mcp/Servers/SupportServer.php @@ -7,7 +7,7 @@ use Laravel\Mcp\Server\Attributes\Instructions; use Laravel\Mcp\Server\Attributes\Name; use Laravel\Mcp\Server\Attributes\Version; -use RefactorCircus\Cortex\Domains\McpServer\Support\Server; +use RefactorCircus\Cortex\Domains\ConcreteServer\Support\Server; use Workbench\App\Domains\Orders\Tools\LookupOrderTool; use Workbench\App\Domains\Support\Tools\CreateTicketTool; use Workbench\App\Domains\Support\Tools\SearchKnowledgeBaseTool; diff --git a/workbench/database/seeders/DatabaseSeeder.php b/workbench/database/seeders/DatabaseSeeder.php index a2ecace..fdd2912 100644 --- a/workbench/database/seeders/DatabaseSeeder.php +++ b/workbench/database/seeders/DatabaseSeeder.php @@ -7,8 +7,8 @@ use RefactorCircus\Cortex\Domains\ConcreteAgent\Actions\UpdateConcreteAgentToolsAction; use RefactorCircus\Cortex\Domains\ConcreteAgent\Data\CreateConcreteAgentVersionData; use RefactorCircus\Cortex\Domains\ConcreteAgent\Data\UpdateConcreteAgentToolsData; -use RefactorCircus\Cortex\Domains\McpServer\Actions\CreateMcpInstructionVersionAction; -use RefactorCircus\Cortex\Domains\McpServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\CreateMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; use RefactorCircus\Cortex\Domains\Tool\Actions\CreateToolDescriptionVersionAction; use RefactorCircus\Cortex\Domains\Tool\Data\CreateToolDescriptionVersionData; use RefactorCircus\Cortex\Domains\VirtualAgent\Actions\CreateVirtualAgentAction; From 7242415973d4f07874a52b0601d02fdb85890564 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:50:54 -0400 Subject: [PATCH 02/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 2 Class-name shims Lazy autoload fallback for the old Domains\McpServer prefix (src/Domains/ConcreteServer/shims.php, listed in autoload.files): aliases Support\Server, Concerns\HasVersionedInstructions, the two models and the two policies on request, and logs ' moved to ' for other old names. Also commits the group 9 composer.json edits (keen in require-dev, its VCS repository, dump-autoload first in the test script). Co-Authored-By: Claude Opus 5.5 (1M context) --- composer.json | 11 +- src/Domains/ConcreteServer/shims.php | 118 ++++++++++++++++++++ tests/Feature/Compat/ClassShimsTest.php | 139 ++++++++++++++++++++++++ tests/Fixtures/OldNamespaceServer.php | 17 +++ tests/Fixtures/OldTraitServer.php | 22 ++++ tests/Fixtures/old-namespace-child.php | 88 +++++++++++++++ 6 files changed, 394 insertions(+), 1 deletion(-) create mode 100644 src/Domains/ConcreteServer/shims.php create mode 100644 tests/Feature/Compat/ClassShimsTest.php create mode 100644 tests/Fixtures/OldNamespaceServer.php create mode 100644 tests/Fixtures/OldTraitServer.php create mode 100644 tests/Fixtures/old-namespace-child.php diff --git a/composer.json b/composer.json index f171d7e..2b42fcd 100644 --- a/composer.json +++ b/composer.json @@ -25,6 +25,7 @@ "laravel/mcp": "^1.0.1" }, "require-dev": { + "refactor-circus/keen": "dev-main", "refactor-circus/pennantplus": "dev-main", "larastan/larastan": "^3.13", "laravel/pao": "^1.1.5", @@ -41,7 +42,10 @@ "autoload": { "psr-4": { "RefactorCircus\\Cortex\\": "src/" - } + }, + "files": [ + "src/Domains/ConcreteServer/shims.php" + ] }, "autoload-dev": { "psr-4": { @@ -85,6 +89,7 @@ "vendor/bin/pest --parallel" ], "test": [ + "@composer dump-autoload", "@analyse", "@lint:check", "@test:types", @@ -140,6 +145,10 @@ { "type": "vcs", "url": "https://github.com/Refactor-Circus/PennantPlus.git" + }, + { + "type": "vcs", + "url": "https://github.com/Refactor-Circus/Keen.git" } ], "conflict": { diff --git a/src/Domains/ConcreteServer/shims.php b/src/Domains/ConcreteServer/shims.php new file mode 100644 index 0000000..f2af2b3 --- /dev/null +++ b/src/Domains/ConcreteServer/shims.php @@ -0,0 +1,118 @@ + moved to " warning is logged when a Laravel logger + * is bound, and the load ends in the usual class-not-found. + * + * The fallback never throws. Each old name is handled at most once per process, + * which guards against recursion and means the new class is autoloaded at most + * once per name; an old name that is already declared is never aliased again. + * With no Laravel application (no bound logger) the warning is skipped. + * + * @deprecated The old `Domains\McpServer` names are removed in the next major. + */ + +namespace RefactorCircus\Cortex\Domains\ConcreteServer; + +use Illuminate\Container\Container; +use Throwable; + +(static function (): void { + $oldPrefix = 'RefactorCircus\Cortex\Domains\McpServer\\'; + $newPrefix = 'RefactorCircus\Cortex\Domains\ConcreteServer\\'; + + $aliases = [ + /** @deprecated Use the ConcreteServer Support\Server; removed in the next major. */ + 'RefactorCircus\Cortex\Domains\McpServer\Support\Server' => Support\Server::class, + /** @deprecated Use the ConcreteServer Concerns\HasVersionedInstructions; removed in the next major. */ + 'RefactorCircus\Cortex\Domains\McpServer\Concerns\HasVersionedInstructions' => Concerns\HasVersionedInstructions::class, + /** @deprecated Use the ConcreteServer Models\McpInstructionModel; removed in the next major. */ + 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel' => Models\McpInstructionModel::class, + /** @deprecated Use the ConcreteServer Models\McpInstructionVersionModel; removed in the next major. */ + 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel' => Models\McpInstructionVersionModel::class, + /** @deprecated Use the ConcreteServer Policies\McpInstructionPolicy; removed in the next major. */ + 'RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionPolicy' => Policies\McpInstructionPolicy::class, + /** @deprecated Use the ConcreteServer Policies\McpInstructionVersionPolicy; removed in the next major. */ + 'RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionVersionPolicy' => Policies\McpInstructionVersionPolicy::class, + ]; + + // PHP class names are case-insensitive, and so is the lookup. + $lookup = array_change_key_case($aliases); + + $declared = static fn (string $class): bool => class_exists($class, false) + || interface_exists($class, false) + || trait_exists($class, false) + || enum_exists($class, false); + + $warn = static function (string $old, string $new): void { + if (! class_exists(Container::class, false)) { + return; + } + + $container = Container::getInstance(); + + if (! $container->bound('log')) { + return; + } + + $container->make('log')->warning( + "{$old} moved to {$new}. Cortex keeps no alias for it: update the reference (see the CHANGELOG).", + ['old' => $old, 'new' => $new], + ); + }; + + /** @var array $requested */ + $requested = []; + + spl_autoload_register(static function (string $class) use ($oldPrefix, $newPrefix, $lookup, $declared, $warn, &$requested): void { + if (strncasecmp($class, $oldPrefix, strlen($oldPrefix)) !== 0) { + return; + } + + $key = strtolower($class); + + if (isset($requested[$key])) { + return; + } + + $requested[$key] = true; + + try { + $new = $lookup[$key] ?? $newPrefix.substr($class, strlen($oldPrefix)); + + // The one autoload of the new name for this old name. + if (! class_exists($new) && ! $declared($new)) { + return; + } + + if (! isset($lookup[$key])) { + $warn($class, $new); + + return; + } + + if ($declared($class)) { + return; + } + + class_alias($new, $class); + } catch (Throwable) { + // A shim must never break autoloading: the load falls through to + // the usual class-not-found. + } + }); +})(); diff --git a/tests/Feature/Compat/ClassShimsTest.php b/tests/Feature/Compat/ClassShimsTest.php new file mode 100644 index 0000000..c7f828e --- /dev/null +++ b/tests/Feature/Compat/ClassShimsTest.php @@ -0,0 +1,139 @@ + + */ +function shimmedClassNames(): array +{ + return [ + 'RefactorCircus\Cortex\Domains\McpServer\Support\Server' => Server::class, + 'RefactorCircus\Cortex\Domains\McpServer\Concerns\HasVersionedInstructions' => HasVersionedInstructions::class, + 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel' => McpInstructionModel::class, + 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel' => McpInstructionVersionModel::class, + 'RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionPolicy' => McpInstructionPolicy::class, + 'RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionVersionPolicy' => McpInstructionVersionPolicy::class, + ]; +} + +function publishOldNamespaceInstructions(string $server, string $content): void +{ + $instruction = McpInstructionModel::query()->create(['server' => $server]); + $version = $instruction->versions()->create(['version' => 1, 'content' => $content]); + + $instruction->published_version_id = $version->getKey(); + $instruction->save(); + + app(PublicationCache::class)->forget(app(PublicationCache::class)->mcpInstructionsKey()); + + app()->forgetScopedInstances(); +} + +it('applies the instructions override to a host server on the old Support\Server', function () { + app(McpServerRegistry::class)->register('old-namespace', OldNamespaceServer::class); + + publishOldNamespaceInstructions('old-namespace', 'Override instructions for the old namespace server.'); + + $context = (new OldNamespaceServer(new FakeTransporter))->createContext(); + + expect($context->instructions)->toBe('Override instructions for the old namespace server.') + ->and(is_subclass_of(OldNamespaceServer::class, Server::class))->toBeTrue(); +}); + +it('applies the instructions override to a host server using the old trait', function () { + app(McpServerRegistry::class)->register('old-trait', OldTraitServer::class); + + publishOldNamespaceInstructions('old-trait', 'Override instructions for the old trait server.'); + + $context = (new OldTraitServer(new FakeTransporter))->createContext(); + + expect($context->instructions)->toBe('Override instructions for the old trait server.') + ->and(class_uses(OldTraitServer::class))->toContain(HasVersionedInstructions::class); +}); + +it('serves code-declared instructions on old-namespace servers without an override', function () { + app(McpServerRegistry::class)->register('old-namespace', OldNamespaceServer::class); + app(McpServerRegistry::class)->register('old-trait', OldTraitServer::class); + + expect((new OldNamespaceServer(new FakeTransporter))->createContext()->instructions) + ->toBe('Code-declared old namespace server instructions.') + ->and((new OldTraitServer(new FakeTransporter))->createContext()->instructions) + ->toBe('Code-declared old trait server instructions.'); +}); + +it('resolves every shimmed old name to its new class', function (string $old, string $new) { + $exists = $new === HasVersionedInstructions::class ? trait_exists($old) : class_exists($old); + + expect($exists)->toBeTrue() + ->and((new ReflectionClass($old))->getName())->toBe($new); +})->with(fn (): array => array_map( + fn (string $old, string $new): array => [$old, $new], + array_keys(shimmedClassNames()), + shimmedClassNames(), +)); + +it('logs where an unshimmed old name moved to and defines no alias for it', function () { + Log::spy(); + + $old = 'RefactorCircus\Cortex\Domains\McpServer\Actions\DeleteMcpInstructionAction'; + $new = 'RefactorCircus\Cortex\Domains\ConcreteServer\Actions\DeleteMcpInstructionAction'; + + expect(class_exists($old))->toBeFalse() + ->and(class_exists($old))->toBeFalse() + ->and(class_exists($old, false))->toBeFalse() + ->and(class_exists($new, false))->toBeTrue(); + + Log::shouldHaveReceived('warning') + ->once() + ->withArgs(fn (string $message): bool => str_contains($message, "{$old} moved to {$new}")); +}); + +it('loads the old names lazily and resolves them in a process with no booted app', function () { + $root = dirname(__DIR__, 3); + + $files = (string) file_get_contents($root.'/vendor/composer/autoload_files.php'); + + expect(str_contains($files, '/'.CORTEX_SHIM_FILE))->toBeTrue( + 'vendor/composer/autoload_files.php does not list '.CORTEX_SHIM_FILE.'. The autoloader is stale: run `composer dump-autoload` and rerun the tests.', + ); + + $result = Process::path($root)->run([PHP_BINARY, $root.'/tests/Fixtures/old-namespace-child.php']); + + expect($result->exitCode())->toBe(0, $result->errorOutput()) + ->and($result->output())->toContain('old-namespace-child: ok'); +}); + +it('lists the shim in autoload.files and marks every shim deprecated', function () { + $root = dirname(__DIR__, 3); + + /** @var array{autoload: array{files?: list}} $composer */ + $composer = json_decode((string) file_get_contents($root.'/composer.json'), true, flags: JSON_THROW_ON_ERROR); + + $shim = (string) file_get_contents($root.'/'.CORTEX_SHIM_FILE); + + expect($composer['autoload']['files'] ?? [])->toContain(CORTEX_SHIM_FILE) + ->and(substr_count($shim, '@deprecated'))->toBeGreaterThanOrEqual(count(shimmedClassNames())); + + foreach (array_keys(shimmedClassNames()) as $old) { + expect($shim)->toMatch('/@deprecated[^\/]*\*\/\s*\''.preg_quote($old, '/').'\'/'); + } +}); diff --git a/tests/Fixtures/OldNamespaceServer.php b/tests/Fixtures/OldNamespaceServer.php new file mode 100644 index 0000000..74a79d7 --- /dev/null +++ b/tests/Fixtures/OldNamespaceServer.php @@ -0,0 +1,17 @@ + 'RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel', + 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel' => 'RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel', +]; + +foreach ($models as $old => $new) { + if (! class_exists($old) || (new ReflectionClass($old))->getName() !== $new) { + throw new RuntimeException("[{$old}] does not resolve to [{$new}]."); + } +} + +fwrite(STDOUT, 'old-namespace-child: ok'.PHP_EOL); From 13fb9a34eddee0e47117c6a8f48f5be1b2431ab6 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:16:41 -0400 Subject: [PATCH 03/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 10 Morph aliases Co-Authored-By: Claude Opus 5.5 (1M context) --- .../ConcreteServerServiceProvider.php | 95 ++++++ tests/Feature/Compat/MorphAliasesTest.php | 300 ++++++++++++++++++ tests/Feature/ModelsTest.php | 5 +- 3 files changed, 398 insertions(+), 2 deletions(-) create mode 100644 tests/Feature/Compat/MorphAliasesTest.php diff --git a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php index fc26e4e..057bb3b 100644 --- a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php +++ b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php @@ -4,12 +4,35 @@ namespace RefactorCircus\Cortex\Domains\ConcreteServer; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\Relation; +use Illuminate\Support\Facades\Log; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpInstructionOverrides; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Keystone\Support\ServiceProvider; +use Throwable; class ConcreteServerServiceProvider extends ServiceProvider { + /** + * The class names the two models had before the domain was renamed from + * `McpServer`. Polymorphic columns and audit entries hold these strings, + * and new rows keep writing them, so stored data stays uniform. + * + * @var array> + */ + private const array MORPH_ALIASES = [ + 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel' => McpInstructionModel::class, + 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel' => McpInstructionVersionModel::class, + ]; + + /** + * Whether this process already ran the morph alias check. + */ + private static bool $morphAliasesChecked = false; + public function register(): void { $this->app->singleton(McpServerRegistry::class); @@ -19,6 +42,78 @@ public function register(): void public function boot(): void { + // Merges into the host's map (never replaces it, never enforces one). + $this->keepMorphAliases(self::MORPH_ALIASES); + + // A host or package may replace the map after Cortex booted. + $this->app->booted(fn () => $this->checkMorphAliases()); + $this->loadApiRoutesFrom(__DIR__.'/routes.php'); } + + /** + * Warn when the morph map no longer resolves an old class name to its + * model (a host replaced the map without Cortex's keys, so stored rows + * stop loading), or when a model writes another alias than its old class + * name (a host re-mapped it, so stored rows mix two strings). + * + * Runs once per process from the `booted` callback; logs one warning per + * broken key and never throws. + * + * @internal + */ + public function checkMorphAliases(): void + { + if (self::$morphAliasesChecked) { + return; + } + + self::$morphAliasesChecked = true; + + foreach (self::MORPH_ALIASES as $old => $model) { + try { + $this->checkMorphAlias($old, $model); + } catch (Throwable) { + // A boot-time diagnostic must never break the application. + } + } + } + + /** + * Let the morph alias check run again in this process. + * + * @internal + */ + public static function resetMorphAliasCheck(): void + { + self::$morphAliasesChecked = false; + } + + /** + * @param class-string $model + */ + private function checkMorphAlias(string $old, string $model): void + { + $resolved = Relation::getMorphedModel($old); + + if ($resolved !== $model) { + Log::warning("Cortex morph alias [{$old}] no longer resolves to [{$model}], so stored rows that name it will not load. Keep it in Relation::morphMap(); see the README on host morph maps.", [ + 'key' => $old, + 'model' => $model, + 'resolved' => $resolved, + ]); + + return; + } + + $written = (new $model)->getMorphClass(); + + if ($written !== $old) { + Log::warning("Cortex model [{$model}] is stored as [{$written}] instead of its morph alias [{$old}], so stored rows mix two strings. Do not map it under another alias; see the README on host morph maps.", [ + 'key' => $old, + 'model' => $model, + 'morph_class' => $written, + ]); + } + } } diff --git a/tests/Feature/Compat/MorphAliasesTest.php b/tests/Feature/Compat/MorphAliasesTest.php new file mode 100644 index 0000000..8ebff73 --- /dev/null +++ b/tests/Feature/Compat/MorphAliasesTest.php @@ -0,0 +1,300 @@ + + */ +function morphAliasMap(): array +{ + return [ + MORPH_ALIAS_OLD_INSTRUCTION => McpInstructionModel::class, + MORPH_ALIAS_OLD_VERSION => McpInstructionVersionModel::class, + ]; +} + +function morphAliasInstruction(): McpInstructionModel +{ + $instruction = McpInstructionModel::query()->create(['server' => 'echo']); + $instruction->versions()->create(['version' => 1, 'content' => 'Stored instructions.']); + + return $instruction; +} + +/** + * A polymorphic row written before the rename: its type column holds the + * old class name as a raw string. + */ +function morphAliasLegacyRow(string $type, string $id): RedirectDomainModel +{ + $key = (string) Str::ulid(); + + DB::table(Tables::name('redirect_domains'))->insert([ + 'id' => $key, + 'domain' => 'legacy-'.strtolower($key).'.example.com', + 'owner_type' => $type, + 'owner_id' => $id, + 'created_at' => now(), + 'updated_at' => now(), + ]); + + return RedirectDomainModel::query()->findOrFail($key); +} + +function morphAliasProvider(): ConcreteServerServiceProvider +{ + $provider = app()->getProvider(ConcreteServerServiceProvider::class); + + expect($provider)->toBeInstanceOf(ConcreteServerServiceProvider::class); + + /** @var ConcreteServerServiceProvider $provider */ + return $provider; +} + +/** + * Boot Keen inside the running app and create its tables, so the audit + * log records Cortex's actions. + */ +function morphAliasBootKeen(): void +{ + app()->register(KeenServiceProvider::class); + + test()->loadMigrationsFrom(dirname(__DIR__, 3).'/vendor/refactor-circus/keen/database/migrations'); +} + +beforeEach(function () { + $this->morphMapBefore = Relation::$morphMap; + + ConcreteServerServiceProvider::resetMorphAliasCheck(); +}); + +afterEach(function () { + Relation::$morphMap = $this->morphMapBefore; + + ConcreteServerServiceProvider::resetMorphAliasCheck(); +}); + +it('maps both old class names to the new models in both directions', function (string $old, string $new) { + expect(Relation::getMorphedModel($old))->toBe($new) + ->and((new $new)->getMorphClass())->toBe($old); +})->with(fn (): array => array_map( + fn (string $old, string $new): array => [$old, $new], + array_keys(morphAliasMap()), + morphAliasMap(), +)); + +it('registers exactly the two Cortex morph keys through the merging map', function () { + $cortex = array_filter( + Relation::morphMap(), + fn (string $class): bool => str_starts_with($class, 'RefactorCircus\\Cortex\\'), + ); + + expect($cortex)->toBe(morphAliasMap()) + ->and(Relation::requiresMorphMap())->toBeFalse(); +}); + +it('resolves a stored polymorphic row holding the old class string to the new model', function () { + $instruction = morphAliasInstruction(); + $version = $instruction->versions()->firstOrFail(); + + $instructionOwned = morphAliasLegacyRow(MORPH_ALIAS_OLD_INSTRUCTION, $instruction->getKey()); + $versionOwned = morphAliasLegacyRow(MORPH_ALIAS_OLD_VERSION, $version->getKey()); + + expect($instructionOwned->owner)->toBeInstanceOf(McpInstructionModel::class) + ->and($instructionOwned->owner?->getKey())->toBe($instruction->getKey()) + ->and($versionOwned->owner)->toBeInstanceOf(McpInstructionVersionModel::class) + ->and($versionOwned->owner?->getKey())->toBe($version->getKey()); +}); + +it('keeps both Cortex keys when a host adds its own morph map entry after boot', function () { + Relation::morphMap(['other' => User::class]); + + expect(Relation::getMorphedModel('other'))->toBe(User::class); + + foreach (morphAliasMap() as $old => $new) { + expect(Relation::getMorphedModel($old))->toBe($new) + ->and((new $new)->getMorphClass())->toBe($old); + } +}); + +it('writes the old class string for new saves', function () { + $instruction = morphAliasInstruction(); + $version = $instruction->versions()->firstOrFail(); + + $instructionOwned = RedirectDomainModel::query()->make(['domain' => 'instruction.example.com']); + $instructionOwned->owner()->associate($instruction)->save(); + + $versionOwned = RedirectDomainModel::query()->make(['domain' => 'version.example.com']); + $versionOwned->owner()->associate($version)->save(); + + $stored = DB::table(Tables::name('redirect_domains'))->pluck('owner_type', 'domain')->all(); + + expect($stored)->toBe([ + 'instruction.example.com' => MORPH_ALIAS_OLD_INSTRUCTION, + 'version.example.com' => MORPH_ALIAS_OLD_VERSION, + ]) + ->and($instructionOwned->fresh()?->owner)->toBeInstanceOf(McpInstructionModel::class) + ->and($versionOwned->fresh()?->owner)->toBeInstanceOf(McpInstructionVersionModel::class); +}); + +it('logs nothing when both old keys resolve', function () { + Log::spy(); + + morphAliasProvider()->checkMorphAliases(); + + Log::shouldNotHaveReceived('warning'); +}); + +it('logs one warning naming the key when an old key no longer resolves, once per process', function () { + Log::spy(); + + unset(Relation::$morphMap[MORPH_ALIAS_OLD_INSTRUCTION]); + + morphAliasProvider()->checkMorphAliases(); + morphAliasProvider()->checkMorphAliases(); + + Log::shouldHaveReceived('warning') + ->once() + ->withArgs(fn (string $message, array $context = []): bool => str_contains($message, MORPH_ALIAS_OLD_INSTRUCTION) + && ($context['key'] ?? null) === MORPH_ALIAS_OLD_INSTRUCTION); +}); + +it('never throws from the morph check', function () { + Log::shouldReceive('warning')->andThrow(new RuntimeException('The log is down.')); + + unset(Relation::$morphMap[MORPH_ALIAS_OLD_VERSION]); + + morphAliasProvider()->checkMorphAliases(); + + expect(true)->toBeTrue(); +}); + +it('warns when a new model is stored under another alias than its old class name', function () { + Log::spy(); + + // A later alias for the same class wins for writes. + Relation::morphMap(['host-instruction' => McpInstructionModel::class]); + + morphAliasProvider()->checkMorphAliases(); + + expect((new McpInstructionModel)->getMorphClass())->toBe('host-instruction'); + + Log::shouldHaveReceived('warning') + ->once() + ->withArgs(fn (string $message, array $context = []): bool => str_contains($message, MORPH_ALIAS_OLD_INSTRUCTION) + && str_contains($message, 'host-instruction') + && ($context['key'] ?? null) === MORPH_ALIAS_OLD_INSTRUCTION); +}); + +it('runs the morph check from the booted callback', function () { + Log::spy(); + + // The app is booted, so the provider's booted callback runs at once: + // the keys resolve, it logs nothing and marks the process as checked. + morphAliasProvider()->boot(); + + unset(Relation::$morphMap[MORPH_ALIAS_OLD_INSTRUCTION]); + + morphAliasProvider()->checkMorphAliases(); + + Log::shouldNotHaveReceived('warning'); + + ConcreteServerServiceProvider::resetMorphAliasCheck(); + + morphAliasProvider()->checkMorphAliases(); + + Log::shouldHaveReceived('warning')->once(); +}); + +it('gives a row loaded from an old morph string the new policy', function () { + $instruction = morphAliasInstruction(); + $loaded = morphAliasLegacyRow(MORPH_ALIAS_OLD_INSTRUCTION, $instruction->getKey())->owner; + + expect($loaded)->toBeInstanceOf(McpInstructionModel::class) + ->and(Gate::getPolicyFor($loaded))->toBeInstanceOf(McpInstructionPolicy::class); + + Gate::policy(McpInstructionModel::class, MorphAliasDenyingMcpInstructionPolicy::class); + + expect(Gate::getPolicyFor($loaded))->toBeInstanceOf(MorphAliasDenyingMcpInstructionPolicy::class); + + Gate::forUser(new GenericUser(['id' => 1]))->authorize('update', $loaded); +})->throws(AuthorizationException::class); + +it('resolves a stored audit entry holding the old class string to the new model', function () { + morphAliasBootKeen(); + + $instruction = morphAliasInstruction(); + + DB::table((new AuditEntryModel)->getTable())->insert([ + 'source' => 'cortex', + 'action' => 'mcp_instruction_version.published', + 'subject_type' => MORPH_ALIAS_OLD_INSTRUCTION, + 'subject_id' => $instruction->getKey(), + 'surface' => 'code', + 'hash' => str_repeat('0', 64), + 'created_at' => now(), + ]); + + $entry = AuditEntryModel::query()->where('subject_type', MORPH_ALIAS_OLD_INSTRUCTION)->firstOrFail(); + + expect($entry->subject)->toBeInstanceOf(McpInstructionModel::class) + ->and($entry->subject?->getKey())->toBe($instruction->getKey()); +})->skip(! class_exists(AuditEntryModel::class), 'refactor-circus/keen is not installed.'); + +it('writes the old class string on audit entries for new saves', function () { + morphAliasBootKeen(); + + $instruction = morphAliasInstruction(); + + app(PublishMcpInstructionVersionAction::class)->execute($instruction, 1); + + $entry = AuditEntryModel::query() + ->where('subject_id', $instruction->getKey()) + ->latest('id') + ->firstOrFail(); + + expect($entry->subject_type)->toBe(MORPH_ALIAS_OLD_INSTRUCTION) + ->and($entry->subject)->toBeInstanceOf(McpInstructionModel::class) + ->and($entry->subject?->getKey())->toBe($instruction->getKey()); +})->skip(! class_exists(AuditEntryModel::class), 'refactor-circus/keen is not installed.'); diff --git a/tests/Feature/ModelsTest.php b/tests/Feature/ModelsTest.php index f10eae2..3e9fa8c 100644 --- a/tests/Feature/ModelsTest.php +++ b/tests/Feature/ModelsTest.php @@ -153,6 +153,7 @@ ConcreteAgentOverrideVersionModel::class, ToolDescriptionModel::class, ToolDescriptionVersionModel::class, - McpInstructionModel::class, - McpInstructionVersionModel::class, + // McpInstructionModel and McpInstructionVersionModel moved from the + // McpServer domain and keep their old class names as morph aliases: + // tests/Feature/Compat/MorphAliasesTest.php covers what they store. ]); From 0a78577dda6d17561d32b91e26b0298f21b271fe Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:23:12 -0400 Subject: [PATCH 04/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 11 Policy-key remap Co-Authored-By: Claude Opus 5.5 (1M context) --- src/CortexServiceProvider.php | 4 + .../ConcreteServerServiceProvider.php | 114 +++++++- tests/Feature/Compat/OldPolicyKeysTest.php | 251 ++++++++++++++++++ .../DenyingOldKeyMcpInstructionPolicy.php | 41 +++ 4 files changed, 406 insertions(+), 4 deletions(-) create mode 100644 tests/Feature/Compat/OldPolicyKeysTest.php create mode 100644 tests/Fixtures/Policies/DenyingOldKeyMcpInstructionPolicy.php diff --git a/src/CortexServiceProvider.php b/src/CortexServiceProvider.php index de36daa..225274b 100644 --- a/src/CortexServiceProvider.php +++ b/src/CortexServiceProvider.php @@ -93,6 +93,10 @@ private function fillMcpRequestsForAgents(): void */ public function boot(): void { + // Policy keys still naming the models by their names from before the + // ConcreteServer rename were already moved to the new classes by + // ConcreteServerServiceProvider::register(), which runs before any + // provider boots. $this->registerPolicies(); // Missing records on Cortex's routes answer a plain "Not found.", as its MCP tools do. diff --git a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php index 057bb3b..221c827 100644 --- a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php +++ b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php @@ -4,6 +4,7 @@ namespace RefactorCircus\Cortex\Domains\ConcreteServer; +use Illuminate\Contracts\Config\Repository; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Facades\Log; @@ -19,11 +20,12 @@ class ConcreteServerServiceProvider extends ServiceProvider /** * The class names the two models had before the domain was renamed from * `McpServer`. Polymorphic columns and audit entries hold these strings, - * and new rows keep writing them, so stored data stays uniform. + * and new rows keep writing them, so stored data stays uniform. A host's + * published `cortex.policies` may still be keyed by them. * * @var array> */ - private const array MORPH_ALIASES = [ + private const array OLD_MODEL_NAMES = [ 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel' => McpInstructionModel::class, 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel' => McpInstructionVersionModel::class, ]; @@ -33,8 +35,21 @@ class ConcreteServerServiceProvider extends ServiceProvider */ private static bool $morphAliasesChecked = false; + /** + * The old `cortex.policies` keys moved by `remapOldPolicyKeys()`, each with + * its new key and whether the host listed that new key as well. Logged + * once from `boot()`. + * + * @var array, both: bool}> + */ + private array $remappedPolicyKeys = []; + public function register(): void { + // Every provider registers before any boots, so the Cortex provider's + // registerPolicies() in boot() already sees the new keys. + $this->remapOldPolicyKeys(); + $this->app->singleton(McpServerRegistry::class); $this->app->scoped(McpInstructionOverrides::class); @@ -42,8 +57,10 @@ public function register(): void public function boot(): void { + $this->warnAboutOldPolicyKeys(); + // Merges into the host's map (never replaces it, never enforces one). - $this->keepMorphAliases(self::MORPH_ALIASES); + $this->keepMorphAliases(self::OLD_MODEL_NAMES); // A host or package may replace the map after Cortex booted. $this->app->booted(fn () => $this->checkMorphAliases()); @@ -51,6 +68,95 @@ public function boot(): void $this->loadApiRoutesFrom(__DIR__.'/routes.php'); } + /** + * Move `cortex.policies` entries keyed by an old model class name to the + * new class, keeping the host's policy class. Without this the Gate would + * never match the old key and the model would keep the bundled allow-all + * policy. When the host lists the new key too, the new key wins. Old + * policy class names given as values resolve through the shims. + * + * Runs from `register()`, before `registerPolicies()` in the Cortex + * provider's `boot()`. + * + * @internal + */ + public function remapOldPolicyKeys(): void + { + $key = $this->package()->configKey('policies'); + $config = $this->app->make(Repository::class); + $policies = $config->get($key); + + if (! is_array($policies)) { + return; + } + + foreach (array_keys($policies) as $listed) { + $new = $this->newModelName((string) $listed); + + if ($new === null) { + continue; + } + + $both = array_key_exists($new, $policies); + + if (! $both) { + $policies[$new] = $policies[$listed]; + } + + unset($policies[$listed]); + + $this->remappedPolicyKeys[(string) $listed] = ['new' => $new, 'both' => $both]; + + // The host named the old class, so alias it now: a host policy + // that type-hints the old model name would otherwise fail its + // parameter check, which never triggers autoloading. + class_exists(ltrim((string) $listed, '\\')); + } + + if ($this->remappedPolicyKeys !== []) { + $config->set($key, $policies); + } + } + + /** + * Log one deprecation warning for each `cortex.policies` key that + * `remapOldPolicyKeys()` moved, then forget them. + * + * @internal + */ + public function warnAboutOldPolicyKeys(): void + { + foreach ($this->remappedPolicyKeys as $old => ['new' => $new, 'both' => $both]) { + $outcome = $both + ? "[{$new}] is listed as well and wins, so the old entry is ignored; remove it." + : "Its policy now applies to [{$new}]; key the entry by [{$new}] instead."; + + Log::warning("Cortex policy key [{$old}] in cortex.policies is deprecated: the model moved to [{$new}]. {$outcome} The old key stops working in the next major release.", [ + 'old' => $old, + 'new' => $new, + ]); + } + + $this->remappedPolicyKeys = []; + } + + /** + * The new model class for an old model class name, or null when the name + * is not one of them. PHP class names ignore case and a leading backslash. + * + * @return class-string|null + */ + private function newModelName(string $name): ?string + { + foreach (self::OLD_MODEL_NAMES as $old => $model) { + if (strcasecmp(ltrim($name, '\\'), $old) === 0) { + return $model; + } + } + + return null; + } + /** * Warn when the morph map no longer resolves an old class name to its * model (a host replaced the map without Cortex's keys, so stored rows @@ -70,7 +176,7 @@ public function checkMorphAliases(): void self::$morphAliasesChecked = true; - foreach (self::MORPH_ALIASES as $old => $model) { + foreach (self::OLD_MODEL_NAMES as $old => $model) { try { $this->checkMorphAlias($old, $model); } catch (Throwable) { diff --git a/tests/Feature/Compat/OldPolicyKeysTest.php b/tests/Feature/Compat/OldPolicyKeysTest.php new file mode 100644 index 0000000..5e2e003 --- /dev/null +++ b/tests/Feature/Compat/OldPolicyKeysTest.php @@ -0,0 +1,251 @@ + 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel', + 'version' => 'RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel', + 'instruction_policy' => 'RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionPolicy', + 'version_policy' => 'RefactorCircus\Cortex\Domains\McpServer\Policies\McpInstructionVersionPolicy', + ]; +} + +/** + * The bundled `cortex.policies` map without the two moved models, as in a + * config file a host published before the rename. + * + * @return array + */ +function policiesPublishedBeforeRename(): array +{ + /** @var array $policies */ + $policies = config('cortex.policies'); + + return Arr::except($policies, [McpInstructionModel::class, McpInstructionVersionModel::class]); +} + +/** + * Replace `cortex.policies` with a host's map, then run what the providers + * run: the remap and its warnings from the ConcreteServer provider, and + * `registerPolicies()` from the Cortex provider. + * + * @param array $policies + */ +function bootWithHostPolicies(array $policies): void +{ + config()->set('cortex.policies', $policies); + + $provider = app()->getProvider(ConcreteServerServiceProvider::class); + + expect($provider)->toBeInstanceOf(ConcreteServerServiceProvider::class); + + /** @var ConcreteServerServiceProvider $provider */ + $provider->remapOldPolicyKeys(); + $provider->warnAboutOldPolicyKeys(); + + (fn () => $this->registerPolicies())->call(app()->getProvider(CortexServiceProvider::class)); +} + +/** + * Whether a logged warning names both the old and the new policy key. + */ +function namesPolicyKeys(string $message, mixed $context, string $old, string $new): bool +{ + return str_contains($message, $old) + && str_contains($message, $new) + && is_array($context) + && ($context['old'] ?? null) === $old + && ($context['new'] ?? null) === $new; +} + +beforeEach(function (): void { + app(McpServerRegistry::class)->register('echo', EchoServer::class); +}); + +it('applies a denying host policy keyed by the old model name over HTTP and MCP', function (): void { + $old = oldPolicyKeyNames(); + + bootWithHostPolicies([ + ...policiesPublishedBeforeRename(), + $old['instruction'] => DenyingOldKeyMcpInstructionPolicy::class, + $old['version'] => $old['version_policy'], + ]); + + $instruction = McpInstructionModel::query()->create(['server' => 'echo']); + + expect(Gate::getPolicyFor(McpInstructionModel::class))->toBeInstanceOf(DenyingOldKeyMcpInstructionPolicy::class); + + // Reading is allowed: the host policy's methods type-hint the old model name. + $this->getJson(route('cortex.servers.instructions.show', 'echo'))->assertOk(); + mcpTool(ShowServerInstructionsTool::class, ['server' => 'echo'])->assertOk(); + + // Changing is refused, not left to the bundled allow-all policy. + $this->postJson(route('cortex.servers.instructions.versions.store', 'echo'), ['content' => 'Guest.']) + ->assertUnauthorized(); + $this->deleteJson(route('cortex.servers.instructions.destroy', 'echo'))->assertUnauthorized(); + + mcpTool(CreateServerInstructionVersionTool::class, ['server' => 'echo', 'content' => 'Guest.']) + ->assertHasErrors(['Unauthorized.']); + mcpTool(DeleteServerInstructionsTool::class, ['server' => 'echo']) + ->assertHasErrors(['Unauthorized.']); + + expect(McpInstructionVersionModel::query()->count())->toBe(0) + ->and($instruction->fresh())->not->toBeNull(); +}); + +it('moves old keys to the new model classes in the config', function (): void { + $old = oldPolicyKeyNames(); + + bootWithHostPolicies([ + ...policiesPublishedBeforeRename(), + $old['instruction'] => DenyingOldKeyMcpInstructionPolicy::class, + $old['version'] => $old['version_policy'], + ]); + + /** @var array $policies */ + $policies = config('cortex.policies'); + + expect($policies)->not->toHaveKey($old['instruction']) + ->and($policies)->not->toHaveKey($old['version']) + ->and($policies[McpInstructionModel::class])->toBe(DenyingOldKeyMcpInstructionPolicy::class) + ->and($policies[McpInstructionVersionModel::class])->toBe($old['version_policy']); +}); + +it('logs one deprecation warning naming the old and new keys per remapped key', function (): void { + $old = oldPolicyKeyNames(); + + Log::spy(); + + bootWithHostPolicies([ + ...policiesPublishedBeforeRename(), + $old['instruction'] => DenyingOldKeyMcpInstructionPolicy::class, + $old['version'] => $old['version_policy'], + ]); + + Log::shouldHaveReceived('warning') + ->withArgs(fn (string $message, mixed $context = []): bool => namesPolicyKeys($message, $context, $old['instruction'], McpInstructionModel::class)) + ->once(); + Log::shouldHaveReceived('warning') + ->withArgs(fn (string $message, mixed $context = []): bool => namesPolicyKeys($message, $context, $old['version'], McpInstructionVersionModel::class)) + ->once(); + Log::shouldHaveReceived('warning')->twice(); + + // The warnings are logged once per boot, not on every later call. + app()->getProvider(ConcreteServerServiceProvider::class)?->warnAboutOldPolicyKeys(); + + Log::shouldHaveReceived('warning')->twice(); +}); + +it('lets the new key win when both keys are listed, and still warns about the old one', function (): void { + $old = oldPolicyKeyNames(); + + Log::spy(); + + bootWithHostPolicies([ + ...policiesPublishedBeforeRename(), + $old['instruction'] => DenyingOldKeyMcpInstructionPolicy::class, + McpInstructionModel::class => McpInstructionPolicy::class, + ]); + + /** @var array $policies */ + $policies = config('cortex.policies'); + + expect(Gate::getPolicyFor(McpInstructionModel::class))->toBeInstanceOf(McpInstructionPolicy::class) + ->and($policies)->not->toHaveKey($old['instruction']) + ->and($policies[McpInstructionModel::class])->toBe(McpInstructionPolicy::class); + + Log::shouldHaveReceived('warning') + ->withArgs(fn (string $message, mixed $context = []): bool => namesPolicyKeys($message, $context, $old['instruction'], McpInstructionModel::class)) + ->once(); + Log::shouldHaveReceived('warning')->once(); + + // The new key's allow-all policy applies, not the old key's denying one. + $this->postJson(route('cortex.servers.instructions.versions.store', 'echo'), ['content' => 'Allowed.']) + ->assertCreated(); +}); + +it('resolves an old policy class name given as the value through the shims', function (): void { + $old = oldPolicyKeyNames(); + + bootWithHostPolicies([ + ...policiesPublishedBeforeRename(), + $old['instruction'] => $old['instruction_policy'], + McpInstructionVersionModel::class => $old['version_policy'], + ]); + + $instructionPolicy = Gate::getPolicyFor(McpInstructionModel::class); + $versionPolicy = Gate::getPolicyFor(McpInstructionVersionModel::class); + + expect($instructionPolicy)->toBeInstanceOf(McpInstructionPolicy::class) + ->and((new ReflectionClass($instructionPolicy))->getName())->toBe(McpInstructionPolicy::class) + ->and($versionPolicy)->toBeInstanceOf(McpInstructionVersionPolicy::class) + ->and((new ReflectionClass($versionPolicy))->getName())->toBe(McpInstructionVersionPolicy::class); + + $this->postJson(route('cortex.servers.instructions.versions.store', 'echo'), ['content' => 'Allowed.']) + ->assertCreated(); +}); + +it('leaves a config without old keys alone and logs nothing', function (): void { + /** @var array $before */ + $before = config('cortex.policies'); + + Log::spy(); + + bootWithHostPolicies($before); + + expect(config('cortex.policies'))->toBe($before) + ->and(Gate::getPolicyFor(McpInstructionModel::class))->toBeInstanceOf(McpInstructionPolicy::class); + + Log::shouldNotHaveReceived('warning'); +}); + +it('remaps while registering, before any provider boots and registers the policies', function (): void { + $old = oldPolicyKeyNames(); + + config()->set('cortex.policies', [ + ...policiesPublishedBeforeRename(), + $old['instruction'] => DenyingOldKeyMcpInstructionPolicy::class, + ]); + + $provider = new ConcreteServerServiceProvider(app()); + $provider->register(); + + /** @var array $policies */ + $policies = config('cortex.policies'); + + expect($policies)->not->toHaveKey($old['instruction']) + ->and($policies[McpInstructionModel::class])->toBe(DenyingOldKeyMcpInstructionPolicy::class); + + Log::spy(); + + $provider->warnAboutOldPolicyKeys(); + + Log::shouldHaveReceived('warning') + ->withArgs(fn (string $message, mixed $context = []): bool => namesPolicyKeys($message, $context, $old['instruction'], McpInstructionModel::class)) + ->once(); +}); diff --git a/tests/Fixtures/Policies/DenyingOldKeyMcpInstructionPolicy.php b/tests/Fixtures/Policies/DenyingOldKeyMcpInstructionPolicy.php new file mode 100644 index 0000000..8d27b0b --- /dev/null +++ b/tests/Fixtures/Policies/DenyingOldKeyMcpInstructionPolicy.php @@ -0,0 +1,41 @@ + Date: Sat, 24 Oct 2026 22:27:08 -0400 Subject: [PATCH 05/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 12 Keen and CI checks Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/tests.yml | 5 + tests/Feature/Compat/KeenInCiTest.php | 120 +++++++++++++++++ .../Compat/OldNamespaceReferencesTest.php | 126 ++++++++++++++++++ 3 files changed, 251 insertions(+) create mode 100644 tests/Feature/Compat/KeenInCiTest.php create mode 100644 tests/Feature/Compat/OldNamespaceReferencesTest.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 6f83014..10a5519 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -50,6 +50,11 @@ jobs: composer update --${{ matrix.stability }} --prefer-dist --no-interaction --no-progress --no-scripts composer run prepare + # Regenerates the autoloader so vendor/composer/autoload_files.php lists the + # src/Domains/ConcreteServer/shims.php compatibility shim before any test runs. + - name: Dump autoloader + run: composer dump-autoload + - name: PHPStan if: runner.os != 'Windows' run: composer analyse diff --git a/tests/Feature/Compat/KeenInCiTest.php b/tests/Feature/Compat/KeenInCiTest.php new file mode 100644 index 0000000..259fc0b --- /dev/null +++ b/tests/Feature/Compat/KeenInCiTest.php @@ -0,0 +1,120 @@ +markTestSkipped('refactor-circus/keen is not installed; the guard only fails when CI is set.'); + } + + $failure = keenInCiFailure($ci, $installed); + + expect($failure)->toBeNull((string) $failure); +}); + +it('fails only when CI is set and Keen is missing', function (string|false $ci, bool $installed, bool $fails): void { + $failure = keenInCiFailure($ci, $installed); + + if ($fails) { + expect($failure)->toContain(AuditEntryModel::class)->toContain('refactor-circus/keen'); + } else { + expect($failure)->toBeNull(); + } +})->with([ + 'CI=true, Keen missing' => ['true', false, true], + 'CI=1, Keen missing' => ['1', false, true], + 'CI=true, Keen installed' => ['true', true, false], + 'CI unset, Keen missing' => [false, false, false], + 'CI empty, Keen missing' => ['', false, false], + 'CI=false, Keen missing' => ['false', false, false], + 'CI=0, Keen missing' => ['0', false, false], +]); + +it('keeps refactor-circus/keen in require-dev with a lock entry', function (): void { + $root = dirname(__DIR__, 3); + + /** @var array{require: array, require-dev: array} $composer */ + $composer = json_decode((string) file_get_contents($root.'/composer.json'), true, flags: JSON_THROW_ON_ERROR); + + /** @var array{packages-dev: list} $lock */ + $lock = json_decode((string) file_get_contents($root.'/composer.lock'), true, flags: JSON_THROW_ON_ERROR); + + expect($composer['require-dev'])->toHaveKey('refactor-circus/keen') + ->and($composer['require'])->not->toHaveKey('refactor-circus/keen') + ->and(array_column($lock['packages-dev'], 'name'))->toContain('refactor-circus/keen'); +}); + +it('regenerates the autoloader first in composer test', function (): void { + $root = dirname(__DIR__, 3); + + /** @var array{scripts: array{test: list}} $composer */ + $composer = json_decode((string) file_get_contents($root.'/composer.json'), true, flags: JSON_THROW_ON_ERROR); + + expect($composer['scripts']['test'][0] ?? null)->toBe('@composer dump-autoload'); +}); + +it('regenerates the autoloader in CI after the install and before the tests', function (): void { + $workflow = str_replace("\r\n", "\n", (string) file_get_contents(dirname(__DIR__, 3).'/.github/workflows/tests.yml')); + + $position = function (string $pattern) use ($workflow): int { + expect(preg_match($pattern, $workflow, $match, PREG_OFFSET_CAPTURE))->toBe(1, "The CI workflow has no step matching {$pattern}."); + + return $match[0][1]; + }; + + $install = $position('/^\s+composer update\b/m'); + $dump = $position('/^\s+run: composer dump-autoload\s*$/m'); + + expect($dump)->toBeGreaterThan($install) + ->toBeLessThan($position('/^\s+run: composer test:unit\s*$/m')) + ->toBeLessThan($position('/^\s+run: vendor\/bin\/pest\s*$/m')); +}); diff --git a/tests/Feature/Compat/OldNamespaceReferencesTest.php b/tests/Feature/Compat/OldNamespaceReferencesTest.php new file mode 100644 index 0000000..6fc51a3 --- /dev/null +++ b/tests/Feature/Compat/OldNamespaceReferencesTest.php @@ -0,0 +1,126 @@ + + */ +const OLD_NAMESPACE_ALLOWLIST = [ + // Group 2: the shim file and its tests and fixtures, including the subprocess child. + 'src/Domains/ConcreteServer/shims.php', + 'tests/Feature/Compat/ClassShimsTest.php', + 'tests/Fixtures/OldNamespaceServer.php', + 'tests/Fixtures/OldTraitServer.php', + 'tests/Fixtures/old-namespace-child.php', + // Groups 10 and 11: the morph aliases and the old policy keys (the old model names in the provider). + 'src/Domains/ConcreteServer/ConcreteServerServiceProvider.php', + // Group 10: the morph-alias and old-row tests. + 'tests/Feature/Compat/MorphAliasesTest.php', + // Group 11: the old policy-key test and its host policy fixture. + 'tests/Feature/Compat/OldPolicyKeysTest.php', + 'tests/Fixtures/Policies/DenyingOldKeyMcpInstructionPolicy.php', +]; + +/** + * Every file under the given folders of $root whose contents name the old + * namespace, as sorted root-relative paths with forward slashes. + * + * @param list $folders + * @return list + */ +function oldNamespaceReferences(string $root, array $folders): array +{ + $found = []; + + foreach ($folders as $folder) { + $files = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($root.DIRECTORY_SEPARATOR.$folder, FilesystemIterator::SKIP_DOTS), + ); + + /** @var SplFileInfo $file */ + foreach ($files as $file) { + if (! $file->isFile()) { + continue; + } + + if (preg_match(OLD_NAMESPACE_PATTERN, (string) file_get_contents($file->getPathname())) === 1) { + $relative = substr($file->getPathname(), strlen($root) + 1); + + $found[] = str_replace(DIRECTORY_SEPARATOR, '/', $relative); + } + } + } + + sort($found); + + return $found; +} + +it('keeps the allowlist to its nine named files', function (): void { + $root = dirname(__DIR__, 3); + + expect(OLD_NAMESPACE_ALLOWLIST)->toHaveCount(9) + ->and(array_unique(OLD_NAMESPACE_ALLOWLIST))->toHaveCount(9); + + foreach (OLD_NAMESPACE_ALLOWLIST as $path) { + expect(is_file($root.'/'.$path))->toBeTrue("Allowlisted file {$path} does not exist."); + } +}); + +it('names the old namespace only in the allowlisted files of src and tests', function (): void { + $root = dirname(__DIR__, 3); + + $allowed = OLD_NAMESPACE_ALLOWLIST; + sort($allowed); + + $found = oldNamespaceReferences($root, ['src', 'tests']); + + expect(array_values(array_diff($found, $allowed)))->toBe([], 'These files name the old Domains namespace but are not compatibility files: move them to ConcreteServer.') + ->and(array_values(array_diff($allowed, $found)))->toBe([], 'These allowlisted files no longer name the old namespace: take them off the allowlist and lower its count.') + ->and($found)->toBe($allowed); +}); + +it('finds the old namespace in both its plain and escaped forms', function (): void { + $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'cortex-old-namespace-'.bin2hex(random_bytes(6)); + $nested = $root.DIRECTORY_SEPARATOR.'src'.DIRECTORY_SEPARATOR.'Nested'; + + mkdir($nested, recursive: true); + + $old = 'RefactorCircus\Cortex\Domains'.'\\'.'McpServer'; + + file_put_contents($root.'/src/Plain.php', "toBe(['src/Nested/Escaped.php', 'src/Plain.php']); + } finally { + foreach (['/src/Plain.php', '/src/Clean.php', '/src/Nested/Escaped.php'] as $file) { + unlink($root.$file); + } + + rmdir($nested); + rmdir($root.'/src'); + rmdir($root); + } +}); From 9dbb2ba3533ad4a3c1c4d16376d980788f7a9634 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:38:30 -0400 Subject: [PATCH 06/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 3 Tools column, registry and tool-override storage Co-Authored-By: Claude Opus 5.5 (1M context) --- config/cortex.php | 20 + ...2_add_tools_to_cortex_mcp_instructions.php | 45 +++ .../ConcreteServerServiceProvider.php | 8 + .../Models/McpInstructionModel.php | 19 +- .../Services/McpServerRegistry.php | 62 +++- .../Services/McpToolOverrides.php | 109 ++++++ .../ConcreteServer/Services/ToolsColumn.php | 36 ++ src/Support/PublicationCache.php | 35 +- src/Support/WarningLimiter.php | 61 ++++ tests/Feature/McpToolOverridesTest.php | 344 ++++++++++++++++++ tests/Feature/ToolsMigrationTest.php | 143 ++++++++ tests/Feature/WarningLimiterTest.php | 247 +++++++++++++ tests/Fixtures/GroupedToolsServer.php | 30 ++ tests/Fixtures/NamedMcpTool.php | 33 ++ .../McpServerRegistryDefaultToolsTest.php | 87 +++++ 15 files changed, 1271 insertions(+), 8 deletions(-) create mode 100644 database/migrations/2026_10_23_000002_add_tools_to_cortex_mcp_instructions.php create mode 100644 src/Domains/ConcreteServer/Services/McpToolOverrides.php create mode 100644 src/Domains/ConcreteServer/Services/ToolsColumn.php create mode 100644 src/Support/WarningLimiter.php create mode 100644 tests/Feature/McpToolOverridesTest.php create mode 100644 tests/Feature/ToolsMigrationTest.php create mode 100644 tests/Feature/WarningLimiterTest.php create mode 100644 tests/Fixtures/GroupedToolsServer.php create mode 100644 tests/Fixtures/NamedMcpTool.php create mode 100644 tests/Unit/McpServerRegistryDefaultToolsTest.php diff --git a/config/cortex.php b/config/cortex.php index 74fc844..9789da5 100644 --- a/config/cortex.php +++ b/config/cortex.php @@ -176,6 +176,26 @@ 'servers' => [ // 'support' => \App\Mcp\SupportServer::class, ], + + /* + |---------------------------------------------------------------------- + | MCP Warning Rate Limit + |---------------------------------------------------------------------- + | + | warning_ttl: How long, in seconds, Cortex stays quiet about a stored + | server override it cannot serve as saved once it has + | logged it: a stale, failing or ambiguous tool entry, + | a tools value that is not a list, the missing `tools` + | column, or a failed server context rebuild. Each logs + | once per server and entry per window, across requests, + | through the publication cache store, so use a store + | every node shares. Default 3600 (one hour); values + | below 1 count as 1. Lower it while fixing overrides, + | raise it to quiet a busy log. + | + */ + + 'warning_ttl' => 3600, ], /* diff --git a/database/migrations/2026_10_23_000002_add_tools_to_cortex_mcp_instructions.php b/database/migrations/2026_10_23_000002_add_tools_to_cortex_mcp_instructions.php new file mode 100644 index 0000000..3f1fcdb --- /dev/null +++ b/database/migrations/2026_10_23_000002_add_tools_to_cortex_mcp_instructions.php @@ -0,0 +1,45 @@ +json('tools')->nullable()->after('published_version_id'); + }); + } + + public function down(): void + { + $table = Tables::name('mcp_instructions'); + + if (! Schema::hasColumn($table, 'tools')) { + return; + } + + Schema::table($table, function (Blueprint $table): void { + $table->dropColumn('tools'); + }); + } +}; diff --git a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php index 221c827..a5e1026 100644 --- a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php +++ b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php @@ -12,6 +12,8 @@ use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpInstructionOverrides; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpToolOverrides; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\ToolsColumn; use RefactorCircus\Keystone\Support\ServiceProvider; use Throwable; @@ -53,6 +55,12 @@ public function register(): void $this->app->singleton(McpServerRegistry::class); $this->app->scoped(McpInstructionOverrides::class); + + $this->app->scoped(McpToolOverrides::class); + + // Checked once per process; a worker sees a newly run migration after + // it restarts. + $this->app->singleton(ToolsColumn::class); } public function boot(): void diff --git a/src/Domains/ConcreteServer/Models/McpInstructionModel.php b/src/Domains/ConcreteServer/Models/McpInstructionModel.php index b020edf..684c8bb 100644 --- a/src/Domains/ConcreteServer/Models/McpInstructionModel.php +++ b/src/Domains/ConcreteServer/Models/McpInstructionModel.php @@ -15,13 +15,15 @@ use RefactorCircus\Keystone\Models\Concerns\DispatchesModelEvents; /** - * A versioned instructions override for a registered MCP server, keyed by - * the server's registered name. The published version's content replaces - * the instructions the server class declares in code. + * The overrides for a registered MCP server, keyed by the server's + * registered name. The published version's content replaces the + * instructions the server class declares in code, and a non-null `tools` + * list replaces its code-declared tools (an empty list serves none). * * @property string $id * @property string $server * @property string|null $published_version_id + * @property list|null $tools * @property Carbon|null $created_at * @property Carbon|null $updated_at */ @@ -36,6 +38,7 @@ final class McpInstructionModel extends Model protected $fillable = [ 'server', + 'tools', ]; public function getTable(): string @@ -43,6 +46,16 @@ public function getTable(): string return Tables::name('mcp_instructions'); } + /** + * @return array + */ + protected function casts(): array + { + return [ + 'tools' => 'array', + ]; + } + /** * @return HasMany */ diff --git a/src/Domains/ConcreteServer/Services/McpServerRegistry.php b/src/Domains/ConcreteServer/Services/McpServerRegistry.php index 4747a43..9efa9a4 100644 --- a/src/Domains/ConcreteServer/Services/McpServerRegistry.php +++ b/src/Domains/ConcreteServer/Services/McpServerRegistry.php @@ -10,17 +10,24 @@ use Laravel\Mcp\Server as McpServer; use Laravel\Mcp\Server\Attributes\Instructions; use Laravel\Mcp\Server\Attributes\Name; +use Laravel\Mcp\Server\Tool as McpTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Exceptions\McpServerNotFoundException; use RefactorCircus\Cortex\Mcp\CortexServer; use ReflectionClass; /** - * Registry of MCP servers whose instructions Cortex can override. Server - * classes are never instantiated here (their constructor requires a - * transport) — names and default instructions are read via reflection. + * Registry of MCP servers whose instructions and tools Cortex can override. + * Server classes are never instantiated here (their constructor requires a + * transport) — names, default instructions and default tools are read via + * reflection. */ final class McpServerRegistry { + /** + * The name Cortex's own server is always registered under. + */ + private const string CORTEX = 'cortex'; + /** * @var array> */ @@ -108,6 +115,44 @@ public function defaultInstructions(string $name): string return is_string($default) ? $default : ''; } + /** + * The names of the tools the server class declares in code, in + * declaration order, before any tool override is applied. Read from the + * class's `$tools` default without building the server: ToolSearch + * groups are flattened and each tool is named by its `name()`. + * + * Tools a server adds at runtime (in its constructor or `boot()`) are + * not seen here; serving builds the code tools from the server itself. + * + * @return list + */ + public function defaultTools(string $name): array + { + $default = (new ReflectionClass($this->get($name)))->getProperty('tools')->getDefaultValue(); + + $names = []; + + foreach (is_array($default) ? $default : [] as $entry) { + foreach (is_array($entry) ? $entry : [$entry] as $tool) { + $names[] = $this->toolName($tool); + } + } + + return $names; + } + + /** + * Whether Cortex may override the server's tool list. Every registered + * server may except Cortex's own, by its registered name: the same class + * registered under another name is overridable. + */ + public function supportsToolOverrides(string $name): bool + { + $this->get($name); + + return $name !== self::CORTEX; + } + /** * @return list, instructions: string}> */ @@ -130,7 +175,7 @@ private function loadConfigServers(): void $this->configLoaded = true; - $this->servers['cortex'] = CortexServer::class; + $this->servers[self::CORTEX] = CortexServer::class; /** @var array $configured */ $configured = $this->container->make('config')->get('cortex.mcp.servers', []); @@ -140,6 +185,15 @@ private function loadConfigServers(): void } } + private function toolName(mixed $tool): string + { + if (is_string($tool) && is_a($tool, McpTool::class, true)) { + $tool = $this->container->make($tool); + } + + return $tool instanceof McpTool ? $tool->name() : (is_string($tool) ? $tool : get_debug_type($tool)); + } + /** * Resolve a registration name for a list-style (unkeyed) config entry * from the server's #[Name] attribute, falling back to the class diff --git a/src/Domains/ConcreteServer/Services/McpToolOverrides.php b/src/Domains/ConcreteServer/Services/McpToolOverrides.php new file mode 100644 index 0000000..1b01a7c --- /dev/null +++ b/src/Domains/ConcreteServer/Services/McpToolOverrides.php @@ -0,0 +1,109 @@ +|null + */ + private ?array $overrides = null; + + public function __construct( + private readonly PublicationCache $cache, + private readonly ToolsColumn $column, + private readonly WarningLimiter $warnings, + ) {} + + /** + * The stored tool list for the server (an empty list serves no tools), + * or null to serve its code tools. + * + * @return list|null + */ + public function for(string $server): ?array + { + if (! $this->column->exists()) { + $this->warnings->warn( + $server, + 'column:tools', + sprintf( + 'Cortex serves the code tools of MCP server [%s]: the [%s] table has no tools column. Publish the cortex-migrations tag and run the %s migration.', + $server, + (new McpInstructionModel)->getTable(), + self::MIGRATION, + ), + ['server' => $server], + ); + + return null; + } + + $tools = $this->all()[$server] ?? null; + + if ($tools === null) { + return null; + } + + if (! is_array($tools)) { + $type = get_debug_type($tools); + + $this->warnings->warn( + $server, + 'value_type:'.$type, + sprintf( + 'Cortex ignores the stored tool override of MCP server [%s]: it holds a %s instead of a list of tool names, so the code tools are served.', + $server, + $type, + ), + ['server' => $server, 'value_type' => $type], + ); + + return null; + } + + return array_values(array_filter($tools, is_string(...))); + } + + /** + * Every stored `tools` value by server, as decoded from the column. + * + * @return array + */ + private function all(): array + { + /** @var array */ + return $this->overrides ??= (array) $this->cache->remember( + $this->cache->mcpToolsKey(), + fn (): array => McpInstructionModel::query() + ->whereNotNull('tools') + ->get(['server', 'tools']) + ->mapWithKeys(fn (McpInstructionModel $instruction): array => [ + $instruction->server => $instruction->getAttribute('tools'), + ]) + ->all(), + ); + } +} diff --git a/src/Domains/ConcreteServer/Services/ToolsColumn.php b/src/Domains/ConcreteServer/Services/ToolsColumn.php new file mode 100644 index 0000000..e37f67d --- /dev/null +++ b/src/Domains/ConcreteServer/Services/ToolsColumn.php @@ -0,0 +1,36 @@ + + */ + private array $exists = []; + + public function exists(): bool + { + $model = new McpInstructionModel; + $connection = $model->getConnection(); + $table = $model->getTable(); + + return $this->exists[(string) $connection->getName()."\0".$table] ??= $connection->getSchemaBuilder()->hasColumn($table, 'tools'); + } +} diff --git a/src/Support/PublicationCache.php b/src/Support/PublicationCache.php index fe15e21..8aeb266 100644 --- a/src/Support/PublicationCache.php +++ b/src/Support/PublicationCache.php @@ -12,7 +12,7 @@ /** * Cache for published content (virtual agent prompts, tool description, - * MCP instruction and concrete agent overrides, and the stored OAuth redirect + * MCP instruction and tool, and concrete agent overrides, and the stored OAuth redirect * domains) that only changes when a new version is published or a domain is * added or removed — those actions invalidate explicitly. * @@ -95,6 +95,27 @@ public function mcpInstructionsKey(): string return '{cortex.published}.mcp-instructions'; } + /** + * The concrete MCP server tool overrides. Every action that changes a + * server's `tools` or deletes its override row forgets it. + */ + public function mcpToolsKey(): string + { + return '{cortex.published}.mcp-tools'; + } + + /** + * The rate-limit claim of one warning (see {@see WarningLimiter}): a + * server name plus what the warning is about (a stored entry, a value + * type, a column, an exception class). Both parts are hashed so the key + * stays short whatever they hold, and the Cortex key family keeps a + * cache shared between apps from suppressing another app's warnings. + */ + public function warningKey(string $server, string $subject): string + { + return '{cortex.published}.warning.'.hash('xxh128', $server).'.'.hash('xxh128', $subject); + } + public function redirectDomainsKey(): string { return '{cortex.published}.redirect-domains'; @@ -110,6 +131,18 @@ public function virtualAgentKey(string $agentId): string return '{cortex.published}.virtual-agent.'.$agentId; } + /** + * The store the publication cache reads and writes: `cortex.cache.store` + * when pinned, else Redis when it answers, else the default store. The + * warning limiter claims its keys here, so every node shares them. + * + * @internal + */ + public function store(): Repository + { + return $this->repository(); + } + private function repository(): Repository { /** @var string|null $store */ diff --git a/src/Support/WarningLimiter.php b/src/Support/WarningLimiter.php new file mode 100644 index 0000000..b33ad0b --- /dev/null +++ b/src/Support/WarningLimiter.php @@ -0,0 +1,61 @@ + $context + */ + public function warn(string $server, string $subject, string $message, array $context = []): bool + { + if (! $this->claim($server, $subject)) { + return false; + } + + Log::warning($message, $context); + + return true; + } + + private function claim(string $server, string $subject): bool + { + try { + return $this->cache->store()->add($this->cache->warningKey($server, $subject), true, $this->ttl()); + } catch (Throwable) { + // A cache that cannot rate-limit must not hide the warning. + return true; + } + } + + /** + * The window in seconds, at least one: `Cache::add()` refuses a zero or + * negative TTL, which would silence the warning for good. + */ + private function ttl(): int + { + return max(1, (int) (config('cortex.mcp.warning_ttl') ?? self::DEFAULT_TTL)); + } +} diff --git a/tests/Feature/McpToolOverridesTest.php b/tests/Feature/McpToolOverridesTest.php new file mode 100644 index 0000000..90c319f --- /dev/null +++ b/tests/Feature/McpToolOverridesTest.php @@ -0,0 +1,344 @@ +flush(); +}); + +function freshToolOverrides(): McpToolOverrides +{ + app()->forgetScopedInstances(); + + return app(McpToolOverrides::class); +} + +/** + * Write a raw json value into the tools column, bypassing the model cast. + */ +function insertRawTools(string $server, string $json): void +{ + DB::table(Tables::name('mcp_instructions'))->insert([ + 'id' => (string) Str::ulid(), + 'server' => $server, + 'tools' => $json, + 'created_at' => now(), + 'updated_at' => now(), + ]); +} + +function publishedInstruction(string $server, ?array $tools): McpInstructionModel +{ + $instruction = McpInstructionModel::query()->create(['server' => $server, 'tools' => $tools]); + $version = $instruction->versions()->create(['version' => 1, 'content' => "Published {$server} instructions."]); + $instruction->published_version_id = $version->getKey(); + $instruction->save(); + + return $instruction; +} + +it('maps every row with a tool list, published or not', function (): void { + McpInstructionModel::query()->create(['server' => 'echo', 'tools' => ['echo-mcp-tool', 'renamed-echo']]); + publishedInstruction('plain', ['echo-request-tool']); + publishedInstruction('grouped', null); + + $overrides = freshToolOverrides(); + + expect($overrides->for('echo'))->toBe(['echo-mcp-tool', 'renamed-echo']) + ->and($overrides->for('plain'))->toBe(['echo-request-tool']) + ->and($overrides->for('grouped'))->toBeNull() + ->and($overrides->for('missing'))->toBeNull(); +}); + +it('keeps the stored order of a tool list', function (): void { + McpInstructionModel::query()->create(['server' => 'echo', 'tools' => ['b', 'a', 'c']]); + + expect(freshToolOverrides()->for('echo'))->toBe(['b', 'a', 'c']); +}); + +it('keeps an empty tool list apart from no list', function (): void { + McpInstructionModel::query()->create(['server' => 'echo', 'tools' => []]); + + expect(freshToolOverrides()->for('echo'))->toBe([]); +}); + +it('caches the tool lists under their own key until it is forgotten', function (): void { + $cache = app(PublicationCache::class); + + McpInstructionModel::query()->create(['server' => 'echo', 'tools' => ['first']]); + + expect(freshToolOverrides()->for('echo'))->toBe(['first']) + ->and(Cache::store('array')->get($cache->mcpToolsKey()))->toBe(['echo' => ['first']]); + + // A write that bypasses the actions is not seen until the key is forgotten. + McpInstructionModel::query()->where('server', 'echo')->firstOrFail()->update(['tools' => ['second']]); + + expect(freshToolOverrides()->for('echo'))->toBe(['first']); + + $cache->forget($cache->mcpToolsKey()); + + expect(freshToolOverrides()->for('echo'))->toBe(['second']); +}); + +it('keys the tool lists in the publication cache family, apart from instructions', function (): void { + $cache = app(PublicationCache::class); + + preg_match('/\{[^}]+\}/', $cache->mcpToolsKey(), $keyTag); + preg_match('/\{[^}]+\}/', 'illuminate:cache:flexible:created:'.$cache->mcpToolsKey(), $twinTag); + + expect($cache->mcpToolsKey())->toStartWith('{cortex.published}.') + ->and($cache->mcpToolsKey())->not->toBe($cache->mcpInstructionsKey()) + ->and($twinTag[0])->toBe($keyTag[0]); +}); + +it('reads the map once per request', function (): void { + McpInstructionModel::query()->create(['server' => 'echo', 'tools' => ['first']]); + + $overrides = freshToolOverrides(); + + expect($overrides->for('echo'))->toBe(['first']) + ->and(app(McpToolOverrides::class))->toBe($overrides); + + app(PublicationCache::class)->forget(app(PublicationCache::class)->mcpToolsKey()); + McpInstructionModel::query()->where('server', 'echo')->firstOrFail()->update(['tools' => ['second']]); + + expect($overrides->for('echo'))->toBe(['first']) + ->and(freshToolOverrides()->for('echo'))->toBe(['second']); +}); + +it('reads a stored value that is not a list as no override and warns with its type', function (string $json, string $type): void { + Log::spy(); + + insertRawTools('echo', $json); + + expect(freshToolOverrides()->for('echo'))->toBeNull(); + + Log::shouldHaveReceived('warning')->once()->withArgs( + fn (string $message, array $context): bool => str_contains($message, 'echo') + && $context === ['server' => 'echo', 'value_type' => $type], + ); +})->with([ + 'string' => ['"echo-mcp-tool"', 'string'], + 'int' => ['42', 'int'], + 'bool' => ['true', 'bool'], +]); + +it('rate-limits the corrupt value warning across requests', function (): void { + Log::spy(); + + insertRawTools('echo', '"echo-mcp-tool"'); + + freshToolOverrides()->for('echo'); + freshToolOverrides()->for('echo'); + + Log::shouldHaveReceived('warning')->once(); + + Cache::store('array')->flush(); + freshToolOverrides()->for('echo'); + + Log::shouldHaveReceived('warning')->twice(); +}); + +it('serves the map and logs the corrupt value warning when the cache store throws', function (): void { + $store = new class implements Store + { + public int $calls = 0; + + public function add(string $key, mixed $value, int $seconds): bool + { + return $this->fail(); + } + + public function get($key) + { + return $this->fail(); + } + + public function many(array $keys) + { + return $this->fail(); + } + + public function put($key, $value, $seconds) + { + return $this->fail(); + } + + public function putMany(array $values, $seconds) + { + return $this->fail(); + } + + public function increment($key, $value = 1) + { + return $this->fail(); + } + + public function decrement($key, $value = 1) + { + return $this->fail(); + } + + public function forever($key, $value) + { + return $this->fail(); + } + + public function touch($key, $seconds) + { + return $this->fail(); + } + + public function forget($key) + { + return $this->fail(); + } + + public function flush() + { + return $this->fail(); + } + + public function getPrefix() + { + return ''; + } + + private function fail(): never + { + $this->calls++; + + throw new RuntimeException('Cache store is down.'); + } + }; + + Cache::extend('throwing', fn () => Cache::repository($store)); + config()->set('cache.stores.throwing', ['driver' => 'throwing']); + config()->set('cortex.cache.store', 'throwing'); + + McpInstructionModel::query()->create(['server' => 'echo', 'tools' => ['echo-mcp-tool']]); + insertRawTools('plain', '"echo-mcp-tool"'); + + Log::spy(); + + $overrides = freshToolOverrides(); + + expect($overrides->for('echo'))->toBe(['echo-mcp-tool']) + ->and($overrides->for('plain'))->toBeNull() + ->and($store->calls)->toBeGreaterThan(0); + + Log::shouldHaveReceived('warning')->once()->with(Mockery::type('string'), ['server' => 'plain', 'value_type' => 'string']); +}); + +describe('without the tools column', function (): void { + beforeEach(function (): void { + publishedInstruction('echo', null); + + Schema::table(Tables::name('mcp_instructions'), function (Blueprint $table): void { + $table->dropColumn('tools'); + }); + + app()->forgetInstance(ToolsColumn::class); + }); + + it('reads no tool override, keeps the instructions override and warns naming the migration', function (): void { + Log::spy(); + + expect(freshToolOverrides()->for('echo'))->toBeNull() + ->and(app(McpInstructionOverrides::class)->for('echo'))->toBe('Published echo instructions.'); + + Log::shouldHaveReceived('warning')->once()->withArgs( + fn (string $message, array $context): bool => str_contains($message, 'add_tools_to_cortex_mcp_instructions') + && $context === ['server' => 'echo'], + ); + }); + + it('rate-limits the missing column warning across requests', function (): void { + Log::spy(); + + freshToolOverrides()->for('echo'); + freshToolOverrides()->for('echo'); + + Log::shouldHaveReceived('warning')->once(); + + $this->travel((int) config('cortex.mcp.warning_ttl') + 1)->seconds(); + freshToolOverrides()->for('echo'); + + Log::shouldHaveReceived('warning')->twice(); + }); +}); + +it('checks the column once per process', function (): void { + $column = app(ToolsColumn::class); + + expect($column->exists())->toBeTrue() + ->and(app(ToolsColumn::class))->toBe($column); + + Schema::table(Tables::name('mcp_instructions'), function (Blueprint $table): void { + $table->dropColumn('tools'); + }); + + $queries = 0; + DB::listen(function () use (&$queries): void { + $queries++; + }); + + // The memo answers; no schema query is made again. + expect($column->exists())->toBeTrue() + ->and($queries)->toBe(0); + + app()->forgetInstance(ToolsColumn::class); + + expect(app(ToolsColumn::class)->exists())->toBeFalse(); +}); + +it('checks the column on the model connection, not the default one', function (): void { + config()->set('database.connections.tenant', [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + 'foreign_key_constraints' => true, + ]); + + // The tenant database has the table but was never given the tools column. + Schema::connection('tenant')->create(Tables::name('mcp_instructions'), function (Blueprint $table): void { + $table->ulid('id')->primary(); + $table->string('server')->unique(); + $table->ulid('published_version_id')->nullable(); + $table->timestamps(); + }); + + $resolver = new ConnectionResolver(['tenant' => DB::connection('tenant')]); + $resolver->setDefaultConnection('tenant'); + $original = Model::getConnectionResolver(); + + Model::setConnectionResolver($resolver); + + try { + expect((new McpInstructionModel)->getConnection()->getName())->toBe('tenant') + ->and(DB::connection()->getName())->toBe('testing') + ->and(app(ToolsColumn::class)->exists())->toBeFalse(); + } finally { + Model::setConnectionResolver($original); + } + + // The default connection keeps its own answer. + expect(app(ToolsColumn::class)->exists())->toBeTrue(); +}); diff --git a/tests/Feature/ToolsMigrationTest.php b/tests/Feature/ToolsMigrationTest.php new file mode 100644 index 0000000..443a951 --- /dev/null +++ b/tests/Feature/ToolsMigrationTest.php @@ -0,0 +1,143 @@ +, 1: string} + */ +function toolsMigrationSteps(): array +{ + $directory = dirname(__DIR__, 2).'/database/migrations'; + + $matches = glob($directory.'/*_add_tools_to_cortex_mcp_instructions.php') ?: []; + + expect($matches)->toHaveCount(1); + + $target = $matches[0]; + $all = glob($directory.'/*.php') ?: []; + sort($all); + + $before = array_values(array_filter($all, fn (string $file): bool => strcmp(basename($file), basename($target)) < 0)); + + return [$before, $target]; +} + +function stagedMigrate(string $path, string $command = 'migrate', array $options = []): void +{ + $exit = Artisan::call($command, [ + '--database' => 'staged', + '--path' => $path, + '--realpath' => true, + '--force' => true, + ...$options, + ]); + + expect($exit)->toBe(0, Artisan::output()); +} + +/** + * @return list + */ +function toolsColumns(?string $connection = null): array +{ + return array_values(array_filter( + Schema::connection($connection)->getColumnListing(Tables::name('mcp_instructions')), + fn (string $column): bool => $column === 'tools', + )); +} + +beforeEach(function (): void { + config()->set('database.connections.staged', [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + 'foreign_key_constraints' => true, + ]); +}); + +it('adds a nullable tools column to existing rows and drops it on rollback', function (): void { + [$before, $target] = toolsMigrationSteps(); + + expect($before)->not->toBeEmpty(); + + foreach ($before as $step) { + stagedMigrate($step); + } + + $table = Tables::name('mcp_instructions'); + $id = (string) Str::ulid(); + + expect(toolsColumns('staged'))->toBe([]); + + DB::connection('staged')->table($table)->insert([ + 'id' => $id, + 'server' => 'echo', + 'published_version_id' => null, + 'created_at' => now(), + 'updated_at' => now(), + ]); + + stagedMigrate($target); + + $row = DB::connection('staged')->table($table)->where('id', $id)->first(); + + expect(toolsColumns('staged'))->toBe(['tools']) + ->and($row)->not->toBeNull() + ->and($row->tools)->toBeNull(); + + stagedMigrate($target, 'migrate:rollback', ['--step' => 1]); + + expect(toolsColumns('staged'))->toBe([]) + ->and(DB::connection('staged')->table($table)->where('id', $id)->value('server'))->toBe('echo'); +}); + +it('is a no-op when the column already exists or is already gone', function (): void { + [, $target] = toolsMigrationSteps(); + + // The suite's database already ran every migration, the tools one too. + expect(toolsColumns())->toBe(['tools']); + + $migration = require $target; + + $migration->up(); + $migration->up(); + + expect(toolsColumns())->toBe(['tools']); + + $migration->down(); + $migration->down(); + + expect(toolsColumns())->toBe([]); + + $migration->up(); + + expect(toolsColumns())->toBe(['tools']); +}); + +it('casts the tools column to an array and lets it be mass assigned', function (): void { + $instruction = McpInstructionModel::query()->create([ + 'server' => 'echo', + 'tools' => ['echo-mcp-tool', 'renamed-echo'], + ]); + + expect($instruction->fresh()?->tools)->toBe(['echo-mcp-tool', 'renamed-echo']) + ->and(McpInstructionModel::query()->create(['server' => 'plain'])->fresh()?->tools)->toBeNull(); +}); + +it('stores an empty tool list apart from no list', function (): void { + $instruction = McpInstructionModel::query()->create(['server' => 'echo', 'tools' => []]); + + expect($instruction->fresh()?->tools)->toBe([]) + ->and(DB::table(Tables::name('mcp_instructions'))->where('server', 'echo')->value('tools'))->toBe('[]'); +}); diff --git a/tests/Feature/WarningLimiterTest.php b/tests/Feature/WarningLimiterTest.php new file mode 100644 index 0000000..bcc7612 --- /dev/null +++ b/tests/Feature/WarningLimiterTest.php @@ -0,0 +1,247 @@ +flush(); + + $this->freezeTime(); + + Log::spy(); +}); + +/** + * Assert the limiter wrote the warning exactly this many times so far. + */ +function expectLimitedWarnings(int $times, string $message = 'stale entry'): void +{ + Log::shouldHaveReceived('warning')->with($message, Mockery::any())->times($times); +} + +function limiterWarns(string $server, string $subject, string $message = 'stale entry'): bool +{ + return app(WarningLimiter::class)->warn($server, $subject, $message, ['server' => $server, 'entry' => $subject]); +} + +it('logs the first warning with its context and suppresses repeats within the window', function (): void { + config()->set('cortex.mcp.warning_ttl', 120); + + expect(limiterWarns('echo', 'gone'))->toBeTrue() + ->and(limiterWarns('echo', 'gone'))->toBeFalse(); + + Log::shouldHaveReceived('warning')->once()->with('stale entry', ['server' => 'echo', 'entry' => 'gone']); +}); + +it('logs again once the configured window has passed', function (): void { + config()->set('cortex.mcp.warning_ttl', 120); + + limiterWarns('echo', 'gone'); + + $this->travel(119)->seconds(); + limiterWarns('echo', 'gone'); + + expectLimitedWarnings(1); + + $this->travel(2)->seconds(); + limiterWarns('echo', 'gone'); + + expectLimitedWarnings(2); +}); + +it('casts the configured window to an int', function (): void { + config()->set('cortex.mcp.warning_ttl', '30'); + + limiterWarns('echo', 'gone'); + + $this->travel(29)->seconds(); + limiterWarns('echo', 'gone'); + + expectLimitedWarnings(1); + + $this->travel(2)->seconds(); + limiterWarns('echo', 'gone'); + + expectLimitedWarnings(2); +}); + +it('falls back to a one hour window when the key is absent', function (): void { + config()->set('cortex.mcp', array_diff_key((array) config('cortex.mcp'), ['warning_ttl' => true])); + + expect(config()->has('cortex.mcp.warning_ttl'))->toBeFalse(); + + limiterWarns('echo', 'gone'); + + $this->travel(3599)->seconds(); + limiterWarns('echo', 'gone'); + + expectLimitedWarnings(1); + + $this->travel(2)->seconds(); + limiterWarns('echo', 'gone'); + + expectLimitedWarnings(2); +}); + +it('ships a one hour window in the package config', function (): void { + $config = require dirname(__DIR__, 2).'/config/cortex.php'; + + expect($config['mcp']['warning_ttl'])->toBe(3600); +}); + +it('clamps the window to at least one second', function (int|string $ttl): void { + config()->set('cortex.mcp.warning_ttl', $ttl); + + // A zero or negative TTL would make Cache::add refuse every claim, so the + // warning would never be written. + expect(limiterWarns('echo', 'gone'))->toBeTrue() + ->and(limiterWarns('echo', 'gone'))->toBeFalse(); + + $this->travel(2)->seconds(); + + expect(limiterWarns('echo', 'gone'))->toBeTrue(); +})->with([0, -5, 'not a number']); + +it('limits each entry and each server independently', function (): void { + expect(limiterWarns('echo', 'first'))->toBeTrue() + ->and(limiterWarns('echo', 'second'))->toBeTrue() + ->and(limiterWarns('plain', 'first'))->toBeTrue() + ->and(limiterWarns('echo', 'first'))->toBeFalse() + ->and(limiterWarns('plain', 'first'))->toBeFalse(); + + expectLimitedWarnings(3); +}); + +it('respects a claim another worker already holds', function (): void { + $cache = app(PublicationCache::class); + + Cache::store('array')->add($cache->warningKey('echo', 'gone'), true, 60); + + expect(limiterWarns('echo', 'gone'))->toBeFalse() + ->and(Cache::store('array')->has($cache->warningKey('echo', 'other')))->toBeFalse() + ->and(limiterWarns('echo', 'other'))->toBeTrue() + ->and(Cache::store('array')->has($cache->warningKey('echo', 'other')))->toBeTrue(); + + expectLimitedWarnings(1); +}); + +it('bounds and prefixes its keys with the Cortex key family', function (): void { + $cache = app(PublicationCache::class); + + $short = $cache->warningKey('echo', 'gone'); + $long = $cache->warningKey(str_repeat('s', 5000), str_repeat('e', 5000)); + + expect($short)->toStartWith('{cortex.published}.') + ->and($long)->toStartWith('{cortex.published}.') + ->and(strlen($long))->toBe(strlen($short)) + ->and(strlen($long))->toBeLessThanOrEqual(128) + ->and($cache->warningKey('echo', 'gone'))->toBe($short) + ->and($cache->warningKey('echo', 'other'))->not->toBe($short) + ->and($cache->warningKey('plain', 'gone'))->not->toBe($short) + // The server and the subject are hashed apart, so they cannot run together. + ->and($cache->warningKey('ab', 'c'))->not->toBe($cache->warningKey('a', 'bc')); +}); + +it('claims through the store the publication cache is pinned to', function (): void { + config()->set('cache.stores.second', ['driver' => 'array']); + config()->set('cortex.cache.store', 'second'); + + limiterWarns('echo', 'gone'); + + $key = app(PublicationCache::class)->warningKey('echo', 'gone'); + + expect(Cache::store('second')->has($key))->toBeTrue() + ->and(Cache::store('array')->has($key))->toBeFalse(); +}); + +it('falls back to logging when the cache store throws', function (): void { + $store = new class implements Store + { + /** @var list */ + public array $calls = []; + + public function add(string $key, mixed $value, int $seconds): bool + { + return $this->fail('add'); + } + + public function get($key) + { + return $this->fail('get'); + } + + public function many(array $keys) + { + return $this->fail('many'); + } + + public function put($key, $value, $seconds) + { + return $this->fail('put'); + } + + public function putMany(array $values, $seconds) + { + return $this->fail('putMany'); + } + + public function increment($key, $value = 1) + { + return $this->fail('increment'); + } + + public function decrement($key, $value = 1) + { + return $this->fail('decrement'); + } + + public function forever($key, $value) + { + return $this->fail('forever'); + } + + public function touch($key, $seconds) + { + return $this->fail('touch'); + } + + public function forget($key) + { + return $this->fail('forget'); + } + + public function flush() + { + return $this->fail('flush'); + } + + public function getPrefix() + { + return ''; + } + + private function fail(string $method): never + { + $this->calls[] = $method; + + throw new RuntimeException('Cache store is down.'); + } + }; + + Cache::extend('throwing', fn () => Cache::repository($store)); + config()->set('cache.stores.throwing', ['driver' => 'throwing']); + config()->set('cortex.cache.store', 'throwing'); + + expect(limiterWarns('echo', 'gone'))->toBeTrue() + ->and(limiterWarns('echo', 'gone'))->toBeTrue() + // The claim is one atomic add, never a get followed by a put. + ->and($store->calls)->toBe(['add', 'add']); + + expectLimitedWarnings(2); +}); diff --git a/tests/Fixtures/GroupedToolsServer.php b/tests/Fixtures/GroupedToolsServer.php new file mode 100644 index 0000000..1067a12 --- /dev/null +++ b/tests/Fixtures/GroupedToolsServer.php @@ -0,0 +1,30 @@ +|array>> + */ + protected array $tools = [ + EchoMcpTool::class, + ToolSearch::class => [ + EchoRequestTool::class, + NamedMcpTool::class, + ], + ]; +} diff --git a/tests/Fixtures/NamedMcpTool.php b/tests/Fixtures/NamedMcpTool.php new file mode 100644 index 0000000..df65480 --- /dev/null +++ b/tests/Fixtures/NamedMcpTool.php @@ -0,0 +1,33 @@ +get('message')); + } + + public function schema(JsonSchema $schema): array + { + return [ + 'message' => $schema->string()->description('The message to echo.')->required(), + ]; + } +} diff --git a/tests/Unit/McpServerRegistryDefaultToolsTest.php b/tests/Unit/McpServerRegistryDefaultToolsTest.php new file mode 100644 index 0000000..0d84d16 --- /dev/null +++ b/tests/Unit/McpServerRegistryDefaultToolsTest.php @@ -0,0 +1,87 @@ +register('grouped', GroupedToolsServer::class); + + expect($registry->defaultTools('grouped'))->toBe([ + 'echo-mcp-tool', + 'echo-request-tool', + 'renamed-echo', + ]); +}); + +it('names each code tool by its name(), not its class basename', function (): void { + $registry = app(McpServerRegistry::class); + $registry->register('grouped', GroupedToolsServer::class); + + expect($registry->defaultTools('grouped')) + ->toContain('renamed-echo') + ->not->toContain('named-mcp-tool'); +}); + +it('flattens the cortex server catalog into its tool names', function (): void { + $expected = array_map( + fn (string $class): string => app($class)->name(), + CortexServer::TOOLS, + ); + + expect(app(McpServerRegistry::class)->defaultTools('cortex'))->toBe(array_values($expected)); +}); + +it('lists no code tools for a server that declares none', function (): void { + $registry = app(McpServerRegistry::class); + $registry->register('echo', EchoServer::class); + + expect($registry->defaultTools('echo'))->toBe([]); +}); + +it('refuses default tools for an unregistered server', function (): void { + app(McpServerRegistry::class)->defaultTools('missing'); +})->throws(McpServerNotFoundException::class); + +it('supports tool overrides on every server but cortex', function (): void { + $registry = app(McpServerRegistry::class); + $registry->register('echo', EchoServer::class); + $registry->register('grouped', GroupedToolsServer::class); + + expect($registry->supportsToolOverrides('cortex'))->toBeFalse() + ->and($registry->supportsToolOverrides('echo'))->toBeTrue() + ->and($registry->supportsToolOverrides('grouped'))->toBeTrue(); +}); + +it('keys the non-overridable rule by registered name, not by server class', function (): void { + // CortexServer is final, so a host cannot subclass it; registering the + // class itself under another name shows the rule follows the name. + $registry = app(McpServerRegistry::class); + $registry->register('cortex-copy', CortexServer::class); + + expect($registry->supportsToolOverrides('cortex-copy'))->toBeTrue() + ->and($registry->supportsToolOverrides('cortex'))->toBeFalse(); +}); + +it('refuses the tool override check for an unregistered server', function (): void { + app(McpServerRegistry::class)->supportsToolOverrides('missing'); +})->throws(McpServerNotFoundException::class); + +it('never instantiates the server class to read its tools', function (): void { + $registry = app(McpServerRegistry::class); + $registry->register('grouped', GroupedToolsServer::class); + + // A server needs a transport to be built; the registry must not ask the + // container for one. + app()->bind(GroupedToolsServer::class, fn () => throw new RuntimeException('server instantiated')); + + expect($registry->defaultTools('grouped'))->toHaveCount(3); +}); From 7e04d784bca607d3cdfb43f7971e710361d4d44d Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:46:35 -0400 Subject: [PATCH 07/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 3 Tools column, registry and tool-override storage A throwing tools-column check reads as no tool override for that call (D-055): McpToolOverrides warns through WarningLimiter (subject column-check:, context server and message) and nothing is memoized, so the next call checks again. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../Services/McpToolOverrides.php | 67 ++++++++++++----- .../ConcreteServer/Services/ToolsColumn.php | 4 +- tests/Feature/McpToolOverridesTest.php | 72 +++++++++++++++++++ 3 files changed, 126 insertions(+), 17 deletions(-) diff --git a/src/Domains/ConcreteServer/Services/McpToolOverrides.php b/src/Domains/ConcreteServer/Services/McpToolOverrides.php index 1b01a7c..22180a2 100644 --- a/src/Domains/ConcreteServer/Services/McpToolOverrides.php +++ b/src/Domains/ConcreteServer/Services/McpToolOverrides.php @@ -7,6 +7,7 @@ use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Cortex\Support\PublicationCache; use RefactorCircus\Cortex\Support\WarningLimiter; +use Throwable; /** * Lookup of concrete MCP server tool overrides: server name to the stored @@ -18,9 +19,10 @@ * memoized per request: bound as a scoped singleton so nothing leaks across * Octane requests. * - * A stored value that is not a list, and a table without the `tools` column - * (the migration was not run), read as no override, with a rate-limited - * warning. + * A stored value that is not a list, a table without the `tools` column + * (the migration was not run) and a column check that throws (for example + * with the connection down) read as no override, with a rate-limited + * warning. The instructions override is read on its own and still applies. */ final class McpToolOverrides { @@ -45,19 +47,7 @@ public function __construct( */ public function for(string $server): ?array { - if (! $this->column->exists()) { - $this->warnings->warn( - $server, - 'column:tools', - sprintf( - 'Cortex serves the code tools of MCP server [%s]: the [%s] table has no tools column. Publish the cortex-migrations tag and run the %s migration.', - $server, - (new McpInstructionModel)->getTable(), - self::MIGRATION, - ), - ['server' => $server], - ); - + if (! $this->hasToolsColumn($server)) { return null; } @@ -87,6 +77,51 @@ public function for(string $server): ?array return array_values(array_filter($tools, is_string(...))); } + /** + * Whether tool overrides can be read for this call. A missing column and + * a check that throws both read as no override, each with a rate-limited + * warning; a throwing check is not remembered, so the next call checks + * again. + */ + private function hasToolsColumn(string $server): bool + { + try { + $exists = $this->column->exists(); + } catch (Throwable $exception) { + $this->warnings->warn( + $server, + 'column-check:'.$exception::class, + sprintf( + 'Cortex serves the code tools of MCP server [%s]: checking the [%s] table for its tools column failed with %s. The check runs again on the next request.', + $server, + (new McpInstructionModel)->getTable(), + $exception::class, + ), + ['server' => $server, 'message' => $exception->getMessage()], + ); + + return false; + } + + if (! $exists) { + $this->warnings->warn( + $server, + 'column:tools', + sprintf( + 'Cortex serves the code tools of MCP server [%s]: the [%s] table has no tools column. Publish the cortex-migrations tag and run the %s migration.', + $server, + (new McpInstructionModel)->getTable(), + self::MIGRATION, + ), + ['server' => $server], + ); + + return false; + } + + return true; + } + /** * Every stored `tools` value by server, as decoded from the column. * diff --git a/src/Domains/ConcreteServer/Services/ToolsColumn.php b/src/Domains/ConcreteServer/Services/ToolsColumn.php index e37f67d..2b29e36 100644 --- a/src/Domains/ConcreteServer/Services/ToolsColumn.php +++ b/src/Domains/ConcreteServer/Services/ToolsColumn.php @@ -16,7 +16,9 @@ * connection may differ from the default one) and is remembered for the * process: the class is a singleton, so an Octane or queue worker checks * once and keeps the answer until it restarts. Only a completed check is - * remembered. + * remembered: a check that throws (the schema query fails, for example with + * the connection down) propagates and leaves nothing behind, so the next + * call checks again. {@see McpToolOverrides} reads that call as no override. */ final class ToolsColumn { diff --git a/tests/Feature/McpToolOverridesTest.php b/tests/Feature/McpToolOverridesTest.php index 90c319f..ffd64ad 100644 --- a/tests/Feature/McpToolOverridesTest.php +++ b/tests/Feature/McpToolOverridesTest.php @@ -285,6 +285,78 @@ private function fail(): never }); }); +describe('when the column check throws', function (): void { + it('reads no tool override, warns once within the window and checks again on the next call', function (): void { + McpInstructionModel::query()->create(['server' => 'echo', 'tools' => ['echo-mcp-tool']]); + app()->forgetInstance(ToolsColumn::class); + + $down = true; + $checks = 0; + + // The schema query fails as it would with the connection down. + DB::connection()->beforeExecuting(function () use (&$down, &$checks): void { + if (! $down) { + return; + } + + $checks++; + + throw new RuntimeException('Connection is down.'); + }); + + Log::spy(); + + $column = app(ToolsColumn::class); + + expect(freshToolOverrides()->for('echo'))->toBeNull() + ->and(freshToolOverrides()->for('echo'))->toBeNull() + // Nothing was memoized: each call asked the schema again. + ->and($checks)->toBe(2) + ->and(app(ToolsColumn::class))->toBe($column); + + Log::shouldHaveReceived('warning')->once()->withArgs( + fn (string $message, array $context): bool => str_contains($message, 'echo') + && $context === ['server' => 'echo', 'message' => 'Connection is down.'], + ); + + $cache = app(PublicationCache::class); + + expect(Cache::store('array')->has($cache->warningKey('echo', 'column-check:'.RuntimeException::class)))->toBeTrue(); + + // Once the check succeeds the same process sees the column and the stored list. + $down = false; + + expect(freshToolOverrides()->for('echo'))->toBe(['echo-mcp-tool']) + ->and($column->exists())->toBeTrue(); + + Log::shouldHaveReceived('warning')->once(); + }); + + it('keeps the instructions override while the column check throws', function (): void { + publishedInstruction('echo', ['echo-mcp-tool']); + app()->forgetInstance(ToolsColumn::class); + + // Warm the instructions map, then take the schema query down. + expect(app(McpInstructionOverrides::class)->for('echo'))->toBe('Published echo instructions.'); + + $down = true; + + DB::connection()->beforeExecuting(function () use (&$down): void { + if ($down) { + throw new RuntimeException('Connection is down.'); + } + }); + + try { + expect(freshToolOverrides()->for('echo'))->toBeNull() + ->and(app(McpInstructionOverrides::class)->for('echo'))->toBe('Published echo instructions.'); + } finally { + // The test's own rollback must reach the database. + $down = false; + } + }); +}); + it('checks the column once per process', function (): void { $column = app(ToolsColumn::class); From 13857579d4effe508123e16216bfb5eaefb199c8 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:03:57 -0400 Subject: [PATCH 08/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 4 Update, clear and delete actions with policy and boot warning Co-Authored-By: Claude Opus 5.5 (1M context) --- config/cortex.php | 17 + .../ClearConcreteServerToolsAction.php | 91 +++++ .../Actions/DeleteMcpInstructionAction.php | 49 ++- .../UpdateConcreteServerToolsAction.php | 93 +++++ .../ConcreteServerServiceProvider.php | 5 + .../Data/ClearConcreteServerToolsData.php | 26 ++ .../Data/UpdateConcreteServerToolsData.php | 104 +++++ .../ConcreteServerToolsClearedActionEvent.php | 22 ++ ...ConcreteServerToolsClearingActionEvent.php | 24 ++ .../ConcreteServerToolsUpdatedActionEvent.php | 23 ++ ...ConcreteServerToolsUpdatingActionEvent.php | 24 ++ .../Policies/McpInstructionPolicy.php | 29 ++ .../Services/GuestToolsWarning.php | 106 +++++ .../ConcreteServerToolsActionsTest.php | 365 ++++++++++++++++++ .../Feature/ConcreteServerToolsCacheTest.php | 303 +++++++++++++++ tests/Feature/ConcreteServerToolsRaceTest.php | 59 +++ .../DeleteMcpInstructionActionTest.php | 174 +++++++++ tests/Feature/EventsTest.php | 2 +- tests/Feature/GuestToolsWarningTest.php | 238 ++++++++++++ .../NoUpdateToolsMcpInstructionPolicy.php | 41 ++ ...PartialUpdateToolsMcpInstructionPolicy.php | 29 ++ tests/Support/FileDatabaseMigrations.php | 66 ++++ 22 files changed, 1887 insertions(+), 3 deletions(-) create mode 100644 src/Domains/ConcreteServer/Actions/ClearConcreteServerToolsAction.php create mode 100644 src/Domains/ConcreteServer/Actions/UpdateConcreteServerToolsAction.php create mode 100644 src/Domains/ConcreteServer/Data/ClearConcreteServerToolsData.php create mode 100644 src/Domains/ConcreteServer/Data/UpdateConcreteServerToolsData.php create mode 100644 src/Domains/ConcreteServer/Events/ConcreteServerToolsClearedActionEvent.php create mode 100644 src/Domains/ConcreteServer/Events/ConcreteServerToolsClearingActionEvent.php create mode 100644 src/Domains/ConcreteServer/Events/ConcreteServerToolsUpdatedActionEvent.php create mode 100644 src/Domains/ConcreteServer/Events/ConcreteServerToolsUpdatingActionEvent.php create mode 100644 src/Domains/ConcreteServer/Services/GuestToolsWarning.php create mode 100644 tests/Feature/ConcreteServerToolsActionsTest.php create mode 100644 tests/Feature/ConcreteServerToolsCacheTest.php create mode 100644 tests/Feature/ConcreteServerToolsRaceTest.php create mode 100644 tests/Feature/DeleteMcpInstructionActionTest.php create mode 100644 tests/Feature/GuestToolsWarningTest.php create mode 100644 tests/Fixtures/Policies/NoUpdateToolsMcpInstructionPolicy.php create mode 100644 tests/Fixtures/Policies/PartialUpdateToolsMcpInstructionPolicy.php create mode 100644 tests/Support/FileDatabaseMigrations.php diff --git a/config/cortex.php b/config/cortex.php index 9789da5..62fb7ed 100644 --- a/config/cortex.php +++ b/config/cortex.php @@ -56,6 +56,23 @@ | reading one needs `view` on it, adding or publishing one needs `update`. | Point a model at your own class to replace its policy. | + | updateTools: The McpInstructionModel ability that overrides or clears a + | concrete MCP server's tool list. The bundled default + | allows guests too, and whoever passes it can put any + | registered Cortex tool in front of every client of that + | server, so outside `local` Cortex logs a warning at boot + | while guests are allowed. A policy of your own without an + | updateTools method denies it. To allow trusted users only: + | + | public function updateTools(?Authenticatable $user, McpInstructionModel $instruction): bool + | { + | if ($user === null) { + | return false; + | } + | + | return $user->can('manage-mcp-tools'); + | } + | */ 'policies' => [ diff --git a/src/Domains/ConcreteServer/Actions/ClearConcreteServerToolsAction.php b/src/Domains/ConcreteServer/Actions/ClearConcreteServerToolsAction.php new file mode 100644 index 0000000..822a74e --- /dev/null +++ b/src/Domains/ConcreteServer/Actions/ClearConcreteServerToolsAction.php @@ -0,0 +1,91 @@ +perform($server); + + ConcreteServerToolsClearedActionEvent::dispatch($server); + } + + private function perform(string $server): void + { + if (! $this->servers->supportsToolOverrides($server)) { + throw ValidationException::withMessages([ + 'server' => "The tools of the [{$server}] server cannot be overridden.", + ]); + } + + DB::transaction(function () use ($server): void { + // Decided from the locked row, so a version created or published + // after the action started keeps the row. + /** @var McpInstructionModel|null $instruction */ + $instruction = McpInstructionModel::query()->where('server', $server)->lockForUpdate()->first(); + + if ($instruction === null || $instruction->tools === null) { + return; + } + + $keys = [$this->cache->mcpToolsKey()]; + + if ($instruction->published_version_id === null && ! $instruction->versions()->exists()) { + $instruction->delete(); + + $keys[] = $this->cache->mcpInstructionsKey(); + } else { + $instruction->tools = null; + $instruction->save(); + } + + DB::afterCommit(fn () => $this->forget(...$keys)); + }); + } + + /** + * Forget cache keys after commit without failing the committed write: + * a store that throws is logged, and the old value is served until the + * key expires or the next forget succeeds. + */ + private function forget(string ...$keys): void + { + foreach ($keys as $key) { + try { + $this->cache->forget($key); + } catch (Throwable $exception) { + Log::warning("Cortex cleared a server tool override but could not clear the cached [{$key}]: the previous value is served until the key expires or the next change clears it.", [ + 'key' => $key, + 'message' => $exception->getMessage(), + ]); + } + } + } +} diff --git a/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php b/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php index d0295cb..66b6460 100644 --- a/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php +++ b/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php @@ -5,11 +5,20 @@ namespace RefactorCircus\Cortex\Domains\ConcreteServer\Actions; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionDeletedActionEvent; use RefactorCircus\Cortex\Domains\ConcreteServer\Events\McpInstructionDeletingActionEvent; use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Cortex\Support\PublicationCache; +use Throwable; +/** + * Deletes a server's instructions override: every version, one model at a + * time (each fires its model events), and the published pointer. The + * override row itself goes only when it holds no tool override, so a saved + * tool list keeps applying. + */ final class DeleteMcpInstructionAction { public function __construct(private readonly PublicationCache $cache) {} @@ -26,9 +35,45 @@ public function execute(McpInstructionModel $instruction): void private function perform(McpInstructionModel $instruction): void { DB::transaction(function () use ($instruction): void { - $instruction->delete(); + // Decided from the locked row, never from the copy passed in, so a + // tool list saved after the action started is not lost. + /** @var McpInstructionModel|null $locked */ + $locked = $instruction->newQuery()->whereKey($instruction->getKey())->lockForUpdate()->first(); - DB::afterCommit(fn () => $this->cache->forget($this->cache->mcpInstructionsKey())); + if ($locked !== null) { + /** @var McpInstructionVersionModel $version */ + foreach ($locked->versions()->lazyById() as $version) { + $version->delete(); + } + + if ($locked->tools === null) { + $locked->delete(); + } elseif ($locked->published_version_id !== null) { + $locked->published_version_id = null; + $locked->save(); + } + } + + DB::afterCommit(fn () => $this->forget($this->cache->mcpInstructionsKey(), $this->cache->mcpToolsKey())); }); } + + /** + * Forget cache keys after commit without failing the committed delete: + * a store that throws is logged, and the old value is served until the + * key expires or the next forget succeeds. + */ + private function forget(string ...$keys): void + { + foreach ($keys as $key) { + try { + $this->cache->forget($key); + } catch (Throwable $exception) { + Log::warning("Cortex deleted server instructions but could not clear the cached [{$key}]: the previous value is served until the key expires or the next change clears it.", [ + 'key' => $key, + 'message' => $exception->getMessage(), + ]); + } + } + } } diff --git a/src/Domains/ConcreteServer/Actions/UpdateConcreteServerToolsAction.php b/src/Domains/ConcreteServer/Actions/UpdateConcreteServerToolsAction.php new file mode 100644 index 0000000..92ce871 --- /dev/null +++ b/src/Domains/ConcreteServer/Actions/UpdateConcreteServerToolsAction.php @@ -0,0 +1,93 @@ +perform($server, $data); + + ConcreteServerToolsUpdatedActionEvent::dispatch($result); + + return $result; + } + + private function perform(string $server, UpdateConcreteServerToolsData $data): McpInstructionModel + { + if (! $this->servers->supportsToolOverrides($server)) { + throw ValidationException::withMessages([ + 'server' => "The tools of the [{$server}] server cannot be overridden.", + ]); + } + + try { + return $this->save($server, $data); + } catch (UniqueConstraintViolationException) { + // A concurrent first save created the row after our read: its + // transaction is gone, so save again, now onto that row. + return $this->save($server, $data); + } + } + + private function save(string $server, UpdateConcreteServerToolsData $data): McpInstructionModel + { + return DB::transaction(function () use ($server, $data): McpInstructionModel { + // Decide create or update from the locked row, never from a read + // made before the transaction. + /** @var McpInstructionModel $instruction */ + $instruction = McpInstructionModel::query()->where('server', $server)->lockForUpdate()->first() + ?? new McpInstructionModel(['server' => $server]); + + $instruction->tools = $data->tools; + $instruction->save(); + + DB::afterCommit(fn () => $this->forget($this->cache->mcpToolsKey())); + + return $instruction; + }); + } + + /** + * Forget a cache key after commit without failing the committed write: + * a store that throws is logged, and the old value is served until the + * key expires or the next forget succeeds. + */ + private function forget(string $key): void + { + try { + $this->cache->forget($key); + } catch (Throwable $exception) { + Log::warning("Cortex saved a server tool list but could not clear the cached [{$key}]: the previous list is served until the key expires or the next change clears it.", [ + 'key' => $key, + 'message' => $exception->getMessage(), + ]); + } + } +} diff --git a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php index a5e1026..bf22e5b 100644 --- a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php +++ b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php @@ -10,6 +10,7 @@ use Illuminate\Support\Facades\Log; use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\GuestToolsWarning; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpInstructionOverrides; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpToolOverrides; @@ -73,6 +74,10 @@ public function boot(): void // A host or package may replace the map after Cortex booted. $this->app->booted(fn () => $this->checkMorphAliases()); + // Once every policy is registered: warn while guests may change a + // server's tool list. + $this->app->booted(fn () => $this->app->make(GuestToolsWarning::class)->check()); + $this->loadApiRoutesFrom(__DIR__.'/routes.php'); } diff --git a/src/Domains/ConcreteServer/Data/ClearConcreteServerToolsData.php b/src/Domains/ConcreteServer/Data/ClearConcreteServerToolsData.php new file mode 100644 index 0000000..adfbd90 --- /dev/null +++ b/src/Domains/ConcreteServer/Data/ClearConcreteServerToolsData.php @@ -0,0 +1,26 @@ +> + */ + public static function rules(string $server): array + { + return []; + } +} diff --git a/src/Domains/ConcreteServer/Data/UpdateConcreteServerToolsData.php b/src/Domains/ConcreteServer/Data/UpdateConcreteServerToolsData.php new file mode 100644 index 0000000..b606216 --- /dev/null +++ b/src/Domains/ConcreteServer/Data/UpdateConcreteServerToolsData.php @@ -0,0 +1,104 @@ +|null $tools + */ + public function __construct( + public ?array $tools, + ) {} + + /** + * Each entry names a tool the same way serving does: a tool the server's + * code declares, by its `name()`, else a registered Cortex tool, by its + * registration name (a code tool wins when both match). Two entries that + * would be served under the same name fail on the later one, so the + * served list never holds duplicates. + * + * @return array> + */ + public static function rules(string $server): array + { + $code = app(McpServerRegistry::class)->defaultTools($server); + $registered = app(ToolRegistry::class)->names(); + + return [ + 'tools' => ['present', 'nullable', 'array', 'list', function (string $attribute, mixed $value, Closure $fail) use ($code, $registered): void { + if (! is_array($value)) { + return; + } + + $served = []; + $entries = []; + + foreach ($value as $index => $entry) { + // Non-strings, unknown entries and repeats fail on their + // own rules below. + if (! is_string($entry) || in_array($entry, $entries, true)) { + continue; + } + + $entries[] = $entry; + $name = self::servedName($entry, $code, $registered); + + if ($name === null) { + continue; + } + + if (array_key_exists($name, $served)) { + $fail("{$attribute}.{$index}", "The entry [{$entry}] is served as [{$name}], like [{$served[$name]}] before it."); + + continue; + } + + $served[$name] = $entry; + } + }], + 'tools.*' => ['string', 'distinct', Rule::in([...$code, ...$registered])], + ]; + } + + /** + * The name a client would see for the entry, or null when it names no + * tool. A registered tool that cannot be built is named by its entry. + * + * @param list $code + * @param list $registered + */ + private static function servedName(string $entry, array $code, array $registered): ?string + { + if (in_array($entry, $code, true)) { + return $entry; + } + + if (! in_array($entry, $registered, true)) { + return null; + } + + $class = collect(app(ToolRegistry::class)->summaries())->firstWhere('name', $entry)['class'] ?? null; + + try { + return is_string($class) ? ToolName::of(app($class)) : $entry; + } catch (Throwable) { + return $entry; + } + } +} diff --git a/src/Domains/ConcreteServer/Events/ConcreteServerToolsClearedActionEvent.php b/src/Domains/ConcreteServer/Events/ConcreteServerToolsClearedActionEvent.php new file mode 100644 index 0000000..70f1c0a --- /dev/null +++ b/src/Domains/ConcreteServer/Events/ConcreteServerToolsClearedActionEvent.php @@ -0,0 +1,22 @@ +can('manage-mcp-tools'); + * } + */ + public function updateTools(?Authenticatable $user, McpInstructionModel $instruction): bool + { + return true; + } } diff --git a/src/Domains/ConcreteServer/Services/GuestToolsWarning.php b/src/Domains/ConcreteServer/Services/GuestToolsWarning.php new file mode 100644 index 0000000..7d222c9 --- /dev/null +++ b/src/Domains/ConcreteServer/Services/GuestToolsWarning.php @@ -0,0 +1,106 @@ +app->runningInConsole() || $this->app->environment('local')) { + return; + } + + $servers = $this->serversOpenToGuests(); + + if ($servers === []) { + return; + } + + Log::warning(sprintf( + 'Cortex lets guests change the tool list of MCP servers [%s]: the %s ability of the McpInstructionModel policy allows guests, so anyone who reaches the Cortex routes or MCP tools can put any registered tool on these servers. See the README section on overriding a concrete server\'s tools for a deny-by-default policy.', + implode(', ', $servers), + self::ABILITY, + ), ['servers' => $servers]); + } catch (Throwable) { + // A boot-time diagnostic must never break the application. + } + } + + /** + * Let the check run again in this process. + * + * @internal + */ + public static function reset(): void + { + self::$checked = false; + } + + /** + * The overridable servers whose tools guests may change. + * + * @return list + */ + private function serversOpenToGuests(): array + { + $servers = array_values(array_filter( + $this->servers->names(), + $this->servers->supportsToolOverrides(...), + )); + + if ($this->config->get('cortex.policies.'.McpInstructionModel::class) === McpInstructionPolicy::class) { + return $servers; + } + + $guest = $this->gate->forUser(null); + + return array_values(array_filter( + $servers, + fn (string $server): bool => $guest->allows(self::ABILITY, new McpInstructionModel(['server' => $server])), + )); + } +} diff --git a/tests/Feature/ConcreteServerToolsActionsTest.php b/tests/Feature/ConcreteServerToolsActionsTest.php new file mode 100644 index 0000000..af15f19 --- /dev/null +++ b/tests/Feature/ConcreteServerToolsActionsTest.php @@ -0,0 +1,365 @@ +register('grouped', GroupedToolsServer::class); + app(McpServerRegistry::class)->register('echo', EchoServer::class); + + app(ToolRegistry::class)->register('echo-cortex', EchoCortexTool::class); + app(ToolRegistry::class)->register('echo-ai', EchoTool::class); +}); + +/** + * The validation errors for a tools update on the server, keyed by field; + * empty when the input passes. + * + * @param array $input + * @return array> + */ +function serverToolsErrors(array $input, string $server = 'grouped'): array +{ + try { + UpdateConcreteServerToolsData::from($input, $server); + } catch (ValidationException $exception) { + return $exception->errors(); + } + + return []; +} + +function updateServerTools(string $server, ?array $tools): McpInstructionModel +{ + return app(UpdateConcreteServerToolsAction::class)->execute($server, new UpdateConcreteServerToolsData($tools)); +} + +function clearServerTools(string $server): void +{ + app(ClearConcreteServerToolsAction::class)->execute($server, new ClearConcreteServerToolsData); +} + +/** + * An override row for the server holding published instructions, with the + * given tool list. + */ +function serverWithInstructions(string $server, ?array $tools): McpInstructionModel +{ + $instruction = McpInstructionModel::query()->create(['server' => $server, 'tools' => $tools]); + $version = $instruction->versions()->create(['version' => 1, 'content' => "Published {$server} instructions."]); + $instruction->published_version_id = $version->getKey(); + $instruction->save(); + + return $instruction->refresh(); +} + +describe('update rules', function (): void { + it('requires the tools key, which may be null or a list', function (): void { + expect(serverToolsErrors([]))->toHaveKey('tools') + ->and(serverToolsErrors(['tools' => 'echo-mcp-tool']))->toHaveKey('tools') + ->and(serverToolsErrors(['tools' => ['first' => 'echo-mcp-tool']]))->toHaveKey('tools') + ->and(serverToolsErrors(['tools' => null]))->toBe([]) + ->and(serverToolsErrors(['tools' => []]))->toBe([]); + }); + + it('accepts the server code tools and registered Cortex tools', function (): void { + expect(serverToolsErrors(['tools' => ['renamed-echo', 'echo-cortex', 'echo-mcp-tool', 'echo-ai']]))->toBe([]); + }); + + it('names code tools by name(), not by class basename', function (): void { + expect(serverToolsErrors(['tools' => ['named-mcp-tool']]))->toHaveKey('tools.0'); + }); + + it('refuses an unknown entry on its own index', function (): void { + $errors = serverToolsErrors(['tools' => ['echo-mcp-tool', 'missing-tool']]); + + expect(array_keys($errors))->toBe(['tools.1']); + }); + + it('refuses an entry that is not a string', function (): void { + expect(serverToolsErrors(['tools' => [42]]))->toHaveKey('tools.0'); + }); + + it('refuses the same entry twice', function (): void { + expect(serverToolsErrors(['tools' => ['echo-mcp-tool', 'echo-mcp-tool']]))->toHaveKey('tools.1'); + }); + + it('refuses the later of two entries served under the same name', function (): void { + // A registered tool reusing the code tool's class is served as echo-mcp-tool too. + app(ToolRegistry::class)->register('echo-alias', EchoMcpTool::class); + + expect(array_keys(serverToolsErrors(['tools' => ['echo-mcp-tool', 'echo-alias']])))->toBe(['tools.1']) + ->and(array_keys(serverToolsErrors(['tools' => ['echo-alias', 'renamed-echo', 'echo-mcp-tool']])))->toBe(['tools.2']); + }); + + it('refuses the later of two registered entries served under the same name', function (): void { + app(ToolRegistry::class)->register('echo-cortex-again', EchoCortexTool::class); + + expect(array_keys(serverToolsErrors(['tools' => ['echo-cortex', 'echo-cortex-again']], 'echo')))->toBe(['tools.1']); + }); + + it('accepts an entry matching both a code tool and a registered tool, as the code tool', function (): void { + // D-021: no rejection and no qualified syntax; serving picks the code tool. + app(ToolRegistry::class)->register('echo-mcp-tool', EchoCortexTool::class); + + expect(serverToolsErrors(['tools' => ['echo-mcp-tool', 'echo-cortex']]))->toBe([]); + }); + + it('offers a server without code tools the registered tools only', function (): void { + expect(serverToolsErrors(['tools' => ['echo-cortex']], 'echo'))->toBe([]) + ->and(serverToolsErrors(['tools' => ['echo-mcp-tool']], 'echo'))->toHaveKey('tools.0'); + }); + + it('names an unknown server', function (): void { + UpdateConcreteServerToolsData::rules('missing'); + })->throws(McpServerNotFoundException::class); +}); + +describe('update action', function (): void { + it('creates the override row with the list in stored order', function (): void { + $instruction = updateServerTools('grouped', ['renamed-echo', 'echo-cortex', 'echo-mcp-tool']); + + expect($instruction->exists)->toBeTrue() + ->and($instruction->server)->toBe('grouped') + ->and($instruction->tools)->toBe(['renamed-echo', 'echo-cortex', 'echo-mcp-tool']) + ->and($instruction->published_version_id)->toBeNull() + ->and(McpInstructionModel::query()->where('server', 'grouped')->count())->toBe(1); + }); + + it('updates the existing row and keeps its instructions', function (): void { + $existing = serverWithInstructions('grouped', ['echo-mcp-tool']); + + $instruction = updateServerTools('grouped', ['renamed-echo']); + + expect($instruction->getKey())->toBe($existing->getKey()) + ->and($instruction->tools)->toBe(['renamed-echo']) + ->and($instruction->published_version_id)->toBe($existing->published_version_id) + ->and($instruction->versions()->count())->toBe(1) + ->and(McpInstructionModel::query()->count())->toBe(1); + }); + + it('stores an empty list as an empty list, apart from null', function (): void { + updateServerTools('grouped', []); + + $raw = DB::table(Tables::name('mcp_instructions'))->where('server', 'grouped')->value('tools'); + + expect($raw)->toBe('[]') + ->and(McpInstructionModel::query()->where('server', 'grouped')->firstOrFail()->tools)->toBe([]); + + updateServerTools('grouped', null); + + expect(DB::table(Tables::name('mcp_instructions'))->where('server', 'grouped')->value('tools'))->toBeNull(); + }); + + it('decides create or update from the row read inside its transaction', function (): void { + // A row that appears after the action started (and before its locked + // re-read) is updated, never duplicated or overwritten. + $created = false; + + Event::listen(ConcreteServerToolsUpdatingActionEvent::class, function () use (&$created): void { + serverWithInstructions('grouped', null); + $created = true; + }); + + $instruction = updateServerTools('grouped', ['echo-mcp-tool']); + + expect($created)->toBeTrue() + ->and(McpInstructionModel::query()->where('server', 'grouped')->count())->toBe(1) + ->and($instruction->tools)->toBe(['echo-mcp-tool']) + ->and($instruction->published_version_id)->not->toBeNull() + ->and($instruction->versions()->count())->toBe(1); + }); + + it('refuses the cortex server with a 422 on the server', function (): void { + try { + updateServerTools('cortex', []); + } catch (ValidationException $exception) { + expect($exception->status)->toBe(422) + ->and($exception->errors())->toHaveKey('server') + ->and(McpInstructionModel::query()->count())->toBe(0); + + return; + } + + $this->fail('The cortex server tool list was overridden.'); + }); + + it('lets a CortexServer registered under another name be overridden', function (): void { + app(McpServerRegistry::class)->register('cortex-copy', CortexServer::class); + + expect(updateServerTools('cortex-copy', [])->tools)->toBe([]); + }); + + it('refuses an unknown server', function (): void { + updateServerTools('missing', []); + })->throws(McpServerNotFoundException::class); + + it('announces the update with its starting and finished events', function (): void { + Event::fake([ConcreteServerToolsUpdatingActionEvent::class, ConcreteServerToolsUpdatedActionEvent::class]); + + $data = new UpdateConcreteServerToolsData(['echo-mcp-tool']); + $instruction = app(UpdateConcreteServerToolsAction::class)->execute('grouped', $data); + + Event::assertDispatched(ConcreteServerToolsUpdatingActionEvent::class, fn ($event): bool => $event->server === 'grouped' && $event->data === $data); + Event::assertDispatched(ConcreteServerToolsUpdatedActionEvent::class, fn ($event): bool => $event->instruction->is($instruction)); + }); +}); + +describe('updateTools ability', function (): void { + it('is allowed by the bundled policy, for guests too', function (): void { + $instruction = new McpInstructionModel(['server' => 'grouped']); + + expect(Gate::forUser(null)->allows('updateTools', $instruction))->toBeTrue() + ->and(Gate::forUser(new GenericUser(['id' => 1]))->allows('updateTools', $instruction))->toBeTrue(); + }); + + it('is its own ability, apart from update', function (): void { + config()->set('cortex.policies.'.McpInstructionModel::class, NoUpdateToolsMcpInstructionPolicy::class); + Gate::policy(McpInstructionModel::class, NoUpdateToolsMcpInstructionPolicy::class); + + $instruction = new McpInstructionModel(['server' => 'grouped']); + + // A host policy without updateTools falls to the Gate default: denied. + foreach ([null, new GenericUser(['id' => 1])] as $user) { + expect(Gate::forUser($user)->allows('update', $instruction))->toBeTrue() + ->and(Gate::forUser($user)->allows('updateTools', $instruction))->toBeFalse(); + } + }); +}); + +describe('clear action', function (): void { + it('sets tools to null and keeps the instructions and versions', function (): void { + $existing = serverWithInstructions('grouped', ['echo-mcp-tool']); + $existing->versions()->create(['version' => 2, 'content' => 'Draft.']); + + clearServerTools('grouped'); + + $instruction = McpInstructionModel::query()->where('server', 'grouped')->firstOrFail(); + + expect($instruction->getKey())->toBe($existing->getKey()) + ->and($instruction->tools)->toBeNull() + ->and($instruction->published_version_id)->toBe($existing->published_version_id) + ->and($instruction->versions()->pluck('version')->sort()->values()->all())->toBe([1, 2]); + }); + + it('removes a tool-only row', function (): void { + updateServerTools('grouped', ['echo-mcp-tool']); + + clearServerTools('grouped'); + + expect(McpInstructionModel::query()->where('server', 'grouped')->exists())->toBeFalse(); + }); + + it('keeps the row when a version is created after the action started', function (): void { + updateServerTools('grouped', ['echo-mcp-tool']); + + $created = false; + + Event::listen(ConcreteServerToolsClearingActionEvent::class, function () use (&$created): void { + McpInstructionModel::query()->where('server', 'grouped')->firstOrFail() + ->versions()->create(['version' => 1, 'content' => 'Written meanwhile.']); + $created = true; + }); + + clearServerTools('grouped'); + + $instruction = McpInstructionModel::query()->where('server', 'grouped')->first(); + + expect($created)->toBeTrue() + ->and($instruction)->not->toBeNull() + ->and($instruction?->tools)->toBeNull() + ->and(McpInstructionVersionModel::query()->count())->toBe(1); + }); + + it('keeps a row whose published pointer is set', function (): void { + $instruction = McpInstructionModel::query()->create(['server' => 'grouped', 'tools' => ['echo-mcp-tool']]); + $instruction->published_version_id = (string) Str::ulid(); + $instruction->save(); + + clearServerTools('grouped'); + + expect(McpInstructionModel::query()->where('server', 'grouped')->firstOrFail()->tools)->toBeNull(); + }); + + it('does nothing for a server without a tool override', function (): void { + clearServerTools('grouped'); + + $existing = serverWithInstructions('echo', null); + $updatedAt = $existing->updated_at?->toIso8601String(); + + $this->travel(5)->minutes(); + + clearServerTools('echo'); + + $instruction = McpInstructionModel::query()->where('server', 'echo')->firstOrFail(); + + expect(McpInstructionModel::query()->where('server', 'grouped')->exists())->toBeFalse() + ->and($instruction->updated_at?->toIso8601String())->toBe($updatedAt) + ->and($instruction->versions()->count())->toBe(1); + }); + + it('refuses the cortex server with a 422 on the server', function (): void { + McpInstructionModel::query()->create(['server' => 'cortex', 'tools' => ['list-tools']]); + + try { + clearServerTools('cortex'); + } catch (ValidationException $exception) { + expect($exception->status)->toBe(422) + ->and($exception->errors())->toHaveKey('server') + ->and(McpInstructionModel::query()->where('server', 'cortex')->firstOrFail()->tools)->toBe(['list-tools']); + + return; + } + + $this->fail('The cortex server tool list was cleared.'); + }); + + it('refuses an unknown server', function (): void { + clearServerTools('missing'); + })->throws(McpServerNotFoundException::class); + + it('takes no input', function (): void { + expect(ClearConcreteServerToolsData::rules('grouped'))->toBe([]) + ->and(ClearConcreteServerToolsData::from([], 'grouped'))->toBeInstanceOf(ClearConcreteServerToolsData::class); + }); + + it('announces the clear with its starting and finished events', function (): void { + updateServerTools('grouped', ['echo-mcp-tool']); + + Event::fake([ConcreteServerToolsClearingActionEvent::class, ConcreteServerToolsClearedActionEvent::class]); + + $data = new ClearConcreteServerToolsData; + app(ClearConcreteServerToolsAction::class)->execute('grouped', $data); + + Event::assertDispatched(ConcreteServerToolsClearingActionEvent::class, fn ($event): bool => $event->server === 'grouped' && $event->data === $data); + Event::assertDispatched(ConcreteServerToolsClearedActionEvent::class, fn ($event): bool => $event->server === 'grouped'); + }); +}); diff --git a/tests/Feature/ConcreteServerToolsCacheTest.php b/tests/Feature/ConcreteServerToolsCacheTest.php new file mode 100644 index 0000000..1f73090 --- /dev/null +++ b/tests/Feature/ConcreteServerToolsCacheTest.php @@ -0,0 +1,303 @@ + + */ + public array $forgets = []; + + public bool $failForgets = false; + + public function forget($key) + { + $this->forgets[] = ['key' => (string) $key, 'level' => DB::transactionLevel()]; + + if ($this->failForgets) { + throw new RuntimeException('Cache store is down.'); + } + + return parent::forget($key); + } +} + +beforeEach(function (): void { + app(McpServerRegistry::class)->register('grouped', GroupedToolsServer::class); + + $this->store = new TransactionLevelRecordingStore; + $store = $this->store; + + Cache::extend('recording', fn () => Cache::repository($store)); + config()->set('cache.stores.recording', ['driver' => 'recording']); + config()->set('cortex.cache.store', 'recording'); +}); + +/** + * Read the tool overrides as a new request would. + * + * @return list|null + */ +function cachedServerTools(string $server = 'grouped'): ?array +{ + app()->forgetScopedInstances(); + + return app(McpToolOverrides::class)->for($server); +} + +function cachedServerInstructions(string $server = 'grouped'): ?string +{ + app()->forgetScopedInstances(); + + return app(McpInstructionOverrides::class)->for($server); +} + +/** + * An override row with published instructions and three versions. + */ +function cachedServerWithInstructions(?array $tools): McpInstructionModel +{ + $instruction = McpInstructionModel::query()->create(['server' => 'grouped', 'tools' => $tools]); + + foreach ([1, 2, 3] as $number) { + $version = $instruction->versions()->create(['version' => $number, 'content' => "Instructions v{$number}."]); + } + + $instruction->published_version_id = $version->getKey(); + $instruction->save(); + + return $instruction->refresh(); +} + +/** + * @return list + */ +function forgetLevels(TransactionLevelRecordingStore $store): array +{ + return array_column($store->forgets, 'level'); +} + +/** + * @return list + */ +function forgottenKeys(TransactionLevelRecordingStore $store): array +{ + return array_values(array_unique(array_column($store->forgets, 'key'))); +} + +describe('update', function (): void { + it('(a) serves the new list on the next read', function (): void { + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); + + expect(cachedServerTools())->toBe(['echo-mcp-tool']); + + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['renamed-echo'])); + + expect(cachedServerTools())->toBe(['renamed-echo']); + }); + + it('(b) forgets the tools key after commit', function (): void { + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); + + expect($this->store->forgets)->not->toBeEmpty() + ->and(forgetLevels($this->store))->each->toBe(0) + ->and(forgottenKeys($this->store))->toBe([app(PublicationCache::class)->mcpToolsKey()]); + }); + + it('(c) forgets nothing and keeps the old list when it rolls back', function (): void { + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); + expect(cachedServerTools())->toBe(['echo-mcp-tool']); + $this->store->forgets = []; + + McpInstructionModel::saved(function (): never { + throw new RuntimeException('Saved listener failed.'); + }); + + expect(fn () => app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['renamed-echo']))) + ->toThrow(RuntimeException::class, 'Saved listener failed.'); + + expect(DB::table((new McpInstructionModel)->getTable())->where('server', 'grouped')->value('tools'))->toBe('["echo-mcp-tool"]') + ->and($this->store->forgets)->toBe([]) + ->and(cachedServerTools())->toBe(['echo-mcp-tool']); + }); + + it('succeeds and logs when the after-commit forget fails', function (): void { + Log::spy(); + $this->store->failForgets = true; + + $instruction = app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); + + expect($instruction->tools)->toBe(['echo-mcp-tool']) + ->and(McpInstructionModel::query()->where('server', 'grouped')->firstOrFail()->tools)->toBe(['echo-mcp-tool']) + ->and($this->store->forgets)->not->toBeEmpty(); + + Log::shouldHaveReceived('warning')->withArgs( + fn (string $message, array $context): bool => ($context['key'] ?? null) === app(PublicationCache::class)->mcpToolsKey() + && ($context['message'] ?? null) === 'Cache store is down.', + )->once(); + }); +}); + +describe('clear', function (): void { + it('(a) serves the code tools on the next read', function (): void { + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); + expect(cachedServerTools())->toBe(['echo-mcp-tool']); + + app(ClearConcreteServerToolsAction::class)->execute('grouped', new ClearConcreteServerToolsData); + + expect(cachedServerTools())->toBeNull(); + }); + + it('(b) forgets after commit: the tools key, and the instructions key when the row goes', function (): void { + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); + $this->store->forgets = []; + + app(ClearConcreteServerToolsAction::class)->execute('grouped', new ClearConcreteServerToolsData); + + $cache = app(PublicationCache::class); + + expect($this->store->forgets)->not->toBeEmpty() + ->and(forgetLevels($this->store))->each->toBe(0) + ->and(forgottenKeys($this->store))->toEqualCanonicalizing([$cache->mcpToolsKey(), $cache->mcpInstructionsKey()]); + }); + + it('(b) forgets only the tools key when the row stays', function (): void { + cachedServerWithInstructions(['echo-mcp-tool']); + $this->store->forgets = []; + + app(ClearConcreteServerToolsAction::class)->execute('grouped', new ClearConcreteServerToolsData); + + expect(forgetLevels($this->store))->each->toBe(0) + ->and(forgottenKeys($this->store))->toBe([app(PublicationCache::class)->mcpToolsKey()]); + }); + + it('(c) forgets nothing and keeps the list when it rolls back', function (): void { + cachedServerWithInstructions(['echo-mcp-tool']); + expect(cachedServerTools())->toBe(['echo-mcp-tool']); + $this->store->forgets = []; + + McpInstructionModel::saved(function (): never { + throw new RuntimeException('Saved listener failed.'); + }); + + expect(fn () => app(ClearConcreteServerToolsAction::class)->execute('grouped', new ClearConcreteServerToolsData)) + ->toThrow(RuntimeException::class, 'Saved listener failed.'); + + expect(McpInstructionModel::query()->where('server', 'grouped')->firstOrFail()->tools)->toBe(['echo-mcp-tool']) + ->and($this->store->forgets)->toBe([]) + ->and(cachedServerTools())->toBe(['echo-mcp-tool']); + }); + + it('succeeds and logs when the after-commit forget fails', function (): void { + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); + + Log::spy(); + $this->store->failForgets = true; + + app(ClearConcreteServerToolsAction::class)->execute('grouped', new ClearConcreteServerToolsData); + + expect(McpInstructionModel::query()->where('server', 'grouped')->exists())->toBeFalse(); + + Log::shouldHaveReceived('warning')->withArgs( + fn (string $message, array $context): bool => ($context['message'] ?? null) === 'Cache store is down.', + )->twice(); + }); +}); + +describe('delete instructions', function (): void { + it('(a) serves code instructions and keeps serving the tool list on the next read', function (): void { + $instruction = cachedServerWithInstructions(['echo-mcp-tool']); + + expect(cachedServerInstructions())->toBe('Instructions v3.') + ->and(cachedServerTools())->toBe(['echo-mcp-tool']); + + app(DeleteMcpInstructionAction::class)->execute($instruction); + + expect(cachedServerInstructions())->toBeNull() + ->and(cachedServerTools())->toBe(['echo-mcp-tool']); + }); + + it('(b) forgets both keys after commit, whether or not the row goes', function (bool $keepsTools): void { + $instruction = cachedServerWithInstructions($keepsTools ? ['echo-mcp-tool'] : null); + $this->store->forgets = []; + + app(DeleteMcpInstructionAction::class)->execute($instruction); + + $cache = app(PublicationCache::class); + + expect(McpInstructionModel::query()->where('server', 'grouped')->exists())->toBe($keepsTools) + ->and($this->store->forgets)->not->toBeEmpty() + ->and(forgetLevels($this->store))->each->toBe(0) + ->and(forgottenKeys($this->store))->toEqualCanonicalizing([$cache->mcpToolsKey(), $cache->mcpInstructionsKey()]); + })->with([ + 'row kept for its tools' => [true], + 'row removed' => [false], + ]); + + it('(c) rolls back when the second version delete throws', function (): void { + $instruction = cachedServerWithInstructions(null); + expect(cachedServerInstructions())->toBe('Instructions v3.'); + $this->store->forgets = []; + + $deletes = 0; + + McpInstructionVersionModel::deleting(function () use (&$deletes): void { + if (++$deletes === 2) { + throw new RuntimeException('Second version delete failed.'); + } + }); + + expect(fn () => app(DeleteMcpInstructionAction::class)->execute($instruction)) + ->toThrow(RuntimeException::class, 'Second version delete failed.'); + + $row = McpInstructionModel::query()->where('server', 'grouped')->first(); + + expect($deletes)->toBe(2) + ->and($row)->not->toBeNull() + ->and($row?->published_version_id)->toBe($instruction->published_version_id) + ->and(McpInstructionVersionModel::query()->count())->toBe(3) + ->and($this->store->forgets)->toBe([]) + ->and(cachedServerInstructions())->toBe('Instructions v3.'); + }); + + it('succeeds and logs when the after-commit forget fails', function (): void { + $instruction = cachedServerWithInstructions(['echo-mcp-tool']); + + Log::spy(); + $this->store->failForgets = true; + + app(DeleteMcpInstructionAction::class)->execute($instruction); + + expect(McpInstructionVersionModel::query()->count())->toBe(0); + + Log::shouldHaveReceived('warning')->withArgs( + fn (string $message, array $context): bool => ($context['message'] ?? null) === 'Cache store is down.', + )->twice(); + }); +}); diff --git a/tests/Feature/ConcreteServerToolsRaceTest.php b/tests/Feature/ConcreteServerToolsRaceTest.php new file mode 100644 index 0000000..e602d33 --- /dev/null +++ b/tests/Feature/ConcreteServerToolsRaceTest.php @@ -0,0 +1,59 @@ +register('grouped', GroupedToolsServer::class); +}); + +it('runs on a file-based SQLite database without a wrapping transaction', function (): void { + expect(DB::connection()->getDriverName())->toBe('sqlite') + ->and(DB::connection()->getDatabaseName())->not->toBe(':memory:') + ->and(is_file(DB::connection()->getDatabaseName()))->toBeTrue() + ->and(DB::transactionLevel())->toBe(0); +}); + +it('survives two first saves colliding on the server unique index', function (): void { + $competed = false; + + // Another first save for the same server lands between the action's + // read and its insert, once. + McpInstructionModel::creating(function (McpInstructionModel $instruction) use (&$competed): void { + if ($competed || $instruction->server !== 'grouped') { + return; + } + + $competed = true; + + DB::table(Tables::name('mcp_instructions'))->insert([ + 'id' => (string) Str::ulid(), + 'server' => 'grouped', + 'tools' => json_encode(['echo-request-tool']), + 'created_at' => now(), + 'updated_at' => now(), + ]); + }); + + $instruction = app(UpdateConcreteServerToolsAction::class) + ->execute('grouped', new UpdateConcreteServerToolsData(['renamed-echo', 'echo-mcp-tool'])); + + $rows = McpInstructionModel::query()->where('server', 'grouped')->get(); + + expect($competed)->toBeTrue() + ->and($rows)->toHaveCount(1) + ->and($rows->first()?->tools)->toBe(['renamed-echo', 'echo-mcp-tool']) + ->and($instruction->tools)->toBe(['renamed-echo', 'echo-mcp-tool']); +}); diff --git a/tests/Feature/DeleteMcpInstructionActionTest.php b/tests/Feature/DeleteMcpInstructionActionTest.php new file mode 100644 index 0000000..50b8751 --- /dev/null +++ b/tests/Feature/DeleteMcpInstructionActionTest.php @@ -0,0 +1,174 @@ +register('grouped', GroupedToolsServer::class); +}); + +/** + * An override built by the usual flows: two instruction versions (the second + * published) and, when given, a saved tool list. + */ +function deletableInstruction(?array $tools): McpInstructionModel +{ + app(CreateMcpInstructionVersionAction::class)->execute('grouped', new CreateMcpInstructionVersionData(content: 'First instructions.')); + app(CreateMcpInstructionVersionAction::class)->execute('grouped', new CreateMcpInstructionVersionData(content: 'Second instructions.', publish: true)); + + if ($tools !== null) { + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData($tools)); + } + + return McpInstructionModel::query()->where('server', 'grouped')->firstOrFail(); +} + +function deleteInstructions(McpInstructionModel $instruction): void +{ + app(DeleteMcpInstructionAction::class)->execute($instruction); + app()->forgetScopedInstances(); +} + +it('keeps a row holding a tool override, without its instructions', function (): void { + $instruction = deletableInstruction(['renamed-echo', 'echo-mcp-tool']); + + app()->forgetScopedInstances(); + expect(app(McpInstructionOverrides::class)->for('grouped'))->toBe('Second instructions.'); + + deleteInstructions($instruction); + + $row = McpInstructionModel::query()->where('server', 'grouped')->first(); + + expect($row)->not->toBeNull() + ->and($row?->getKey())->toBe($instruction->getKey()) + ->and($row?->published_version_id)->toBeNull() + ->and($row?->tools)->toBe(['renamed-echo', 'echo-mcp-tool']) + ->and(McpInstructionVersionModel::query()->count())->toBe(0) + // The tool override still applies; the instructions come from code. + ->and(app(McpToolOverrides::class)->for('grouped'))->toBe(['renamed-echo', 'echo-mcp-tool']) + ->and(app(McpInstructionOverrides::class)->for('grouped'))->toBeNull() + ->and(app(McpServerRegistry::class)->all())->toContain([ + 'name' => 'grouped', + 'class' => GroupedToolsServer::class, + 'instructions' => 'Grouped tools server instructions.', + ]); +}); + +it('keeps a row holding an empty tool override', function (): void { + deleteInstructions(deletableInstruction([])); + + expect(McpInstructionModel::query()->where('server', 'grouped')->firstOrFail()->tools)->toBe([]) + ->and(app(McpToolOverrides::class)->for('grouped'))->toBe([]); +}); + +it('removes a row without a tool override, with its versions', function (): void { + deleteInstructions(deletableInstruction(null)); + + expect(McpInstructionModel::query()->count())->toBe(0) + ->and(McpInstructionVersionModel::query()->count())->toBe(0) + ->and(app(McpInstructionOverrides::class)->for('grouped'))->toBeNull() + ->and(app(McpToolOverrides::class)->for('grouped'))->toBeNull(); +}); + +it('deletes the versions one model at a time, firing their model events', function (bool $keepsTools): void { + $instruction = deletableInstruction($keepsTools ? ['echo-mcp-tool'] : null); + $ids = $instruction->versions()->pluck('id')->sort()->values()->all(); + + $deleting = []; + $deleted = []; + + Event::listen(McpInstructionVersionDeletingEvent::class, function (McpInstructionVersionDeletingEvent $event) use (&$deleting): void { + $deleting[] = $event->version->getKey(); + }); + Event::listen(McpInstructionVersionDeletedEvent::class, function (McpInstructionVersionDeletedEvent $event) use (&$deleted): void { + $deleted[] = $event->version->getKey(); + }); + + deleteInstructions($instruction); + + sort($deleting); + sort($deleted); + + expect($ids)->toHaveCount(2) + ->and($deleting)->toBe($ids) + ->and($deleted)->toBe($ids); +})->with([ + 'row kept for its tools' => [true], + 'row removed' => [false], +]); + +it('audits the delete when Keen is installed', function (): void { + app()->register(KeenServiceProvider::class); + test()->loadMigrationsFrom(dirname(__DIR__, 2).'/vendor/refactor-circus/keen/database/migrations'); + + $instruction = deletableInstruction(['echo-mcp-tool']); + + deleteInstructions($instruction); + + // Keen records action events, one entry per action; the per-version + // deletes show as model events (above), not as entries of their own. + $entries = AuditEntryModel::query() + ->where('source', 'cortex') + ->where('action', 'mcp_instruction.deleted') + ->get(); + + expect($entries)->toHaveCount(1) + ->and($entries->first()?->subject_id)->toBe($instruction->getKey()); +})->skip(! class_exists(AuditEntryModel::class), 'refactor-circus/keen is not installed.'); + +it('keeps the row and its tools when a tools write lands after the action started', function (): void { + $instruction = deletableInstruction(null); + $written = false; + + // The starting event fires before the transaction, so this write lands + // before the action's locked re-read; the action's own copy still has no tools. + Event::listen(McpInstructionDeletingActionEvent::class, function (McpInstructionDeletingActionEvent $event) use (&$written): void { + DB::table(Tables::name('mcp_instructions')) + ->where('id', $event->instruction->getKey()) + ->update(['tools' => json_encode(['echo-request-tool'])]); + + $written = true; + }); + + expect($instruction->tools)->toBeNull(); + + deleteInstructions($instruction); + + $row = McpInstructionModel::query()->where('server', 'grouped')->first(); + + expect($written)->toBeTrue() + ->and($row)->not->toBeNull() + ->and($row?->tools)->toBe(['echo-request-tool']) + ->and($row?->published_version_id)->toBeNull() + ->and(McpInstructionVersionModel::query()->count())->toBe(0) + ->and(app(McpToolOverrides::class)->for('grouped'))->toBe(['echo-request-tool']); +}); + +it('does nothing more when the row is already gone', function (): void { + $instruction = deletableInstruction(null); + + McpInstructionModel::query()->whereKey($instruction->getKey())->delete(); + + deleteInstructions($instruction); + + expect(McpInstructionModel::query()->count())->toBe(0); +}); diff --git a/tests/Feature/EventsTest.php b/tests/Feature/EventsTest.php index eb90721..8146679 100644 --- a/tests/Feature/EventsTest.php +++ b/tests/Feature/EventsTest.php @@ -229,7 +229,7 @@ function recordEvents(string $kind): ArrayObject } } - expect($actions)->toHaveCount(34) + expect($actions)->toHaveCount(36) ->and($unpaired)->toBe([]); }); diff --git a/tests/Feature/GuestToolsWarningTest.php b/tests/Feature/GuestToolsWarningTest.php new file mode 100644 index 0000000..9fbdc7f --- /dev/null +++ b/tests/Feature/GuestToolsWarningTest.php @@ -0,0 +1,238 @@ + + */ + public static array $logged = []; +} + +/** + * Boots an application as a web request would (not in the console), + * capturing what it logs, while `GuestToolsWarningWebBoot::$enabled` is set; + * otherwise leaves the test environment alone. + */ +trait BootsGuestToolsWarningOnTheWeb +{ + protected function defineEnvironment($app): void + { + parent::defineEnvironment($app); + + if (! GuestToolsWarningWebBoot::$enabled) { + return; + } + + $app['config']->set('cortex.mcp.servers', ['echo' => EchoServer::class, 'plain' => PlainServer::class]); + + (fn () => $this->isRunningInConsole = false)->call($app); + + $app['events']->listen(MessageLogged::class, function (MessageLogged $event): void { + GuestToolsWarningWebBoot::$logged[] = $event; + }); + } +} + +uses(BootsGuestToolsWarningOnTheWeb::class); + +/** + * A host policy whose `updateTools` fails, as one that queries a table that + * does not exist yet would. + */ +final class ThrowingUpdateToolsMcpInstructionPolicy +{ + public function updateTools(?Authenticatable $user, McpInstructionModel $instruction): bool + { + throw new RuntimeException('Policy table missing.'); + } +} + +beforeEach(function (): void { + GuestToolsWarning::reset(); + + app(McpServerRegistry::class)->register('echo', EchoServer::class); + app(McpServerRegistry::class)->register('plain', PlainServer::class); +}); + +/** + * Make the running application look like a web request, not a console run. + */ +function guestToolsWarningOnTheWeb(): void +{ + (fn () => $this->isRunningInConsole = false)->call(app()); +} + +/** + * Point `cortex.policies` and the Gate at a host policy for the overrides. + * + * @param class-string $policy + */ +function guestToolsWarningPolicy(string $policy): void +{ + config()->set('cortex.policies.'.McpInstructionModel::class, $policy); + Gate::policy(McpInstructionModel::class, $policy); +} + +function runGuestToolsWarning(): void +{ + app(GuestToolsWarning::class)->check(); +} + +it('logs once through the booted callback on a fresh web boot outside local', function (): void { + GuestToolsWarningWebBoot::$enabled = true; + GuestToolsWarningWebBoot::$logged = []; + + try { + $app = $this->createApplication(); + } finally { + GuestToolsWarningWebBoot::$enabled = false; + + // Hand the facades back to this test's application. + Container::setInstance($this->app); + Facade::clearResolvedInstances(); + Facade::setFacadeApplication($this->app); + } + + $warnings = array_values(array_filter( + GuestToolsWarningWebBoot::$logged, + fn (MessageLogged $event): bool => $event->level === 'warning' && str_contains($event->message, 'updateTools'), + )); + + expect($app->runningInConsole())->toBeFalse() + ->and($app->environment('local'))->toBeFalse() + ->and($warnings)->toHaveCount(1) + ->and($warnings[0]->context)->toBe(['servers' => ['echo', 'plain']]); +}); + +it('names every overridable server with the bundled policy', function (): void { + guestToolsWarningOnTheWeb(); + Log::spy(); + + runGuestToolsWarning(); + + Log::shouldHaveReceived('warning')->once()->withArgs( + fn (string $message, array $context): bool => str_contains($message, 'updateTools') + && str_contains($message, 'README') + && $context === ['servers' => ['echo', 'plain']], + ); +}); + +it('reads the bundled policy from the config without asking the Gate', function (): void { + guestToolsWarningOnTheWeb(); + Log::spy(); + + $asked = 0; + Gate::before(function () use (&$asked): ?bool { + $asked++; + + return null; + }); + + runGuestToolsWarning(); + + expect($asked)->toBe(0); + Log::shouldHaveReceived('warning')->once(); +}); + +it('logs nothing in the local environment', function (): void { + guestToolsWarningOnTheWeb(); + app()['env'] = 'local'; + Log::spy(); + + runGuestToolsWarning(); + + Log::shouldNotHaveReceived('warning'); +}); + +it('logs nothing in the console', function (): void { + expect(app()->runningInConsole())->toBeTrue(); + + Log::spy(); + + runGuestToolsWarning(); + + Log::shouldNotHaveReceived('warning'); +}); + +it('logs nothing when a host policy denies guests updateTools', function (): void { + guestToolsWarningOnTheWeb(); + guestToolsWarningPolicy(NoUpdateToolsMcpInstructionPolicy::class); + Log::spy(); + + runGuestToolsWarning(); + + Log::shouldNotHaveReceived('warning'); +}); + +it('neither fails nor logs when the policy throws', function (): void { + guestToolsWarningOnTheWeb(); + guestToolsWarningPolicy(ThrowingUpdateToolsMcpInstructionPolicy::class); + Log::spy(); + + runGuestToolsWarning(); + + Log::shouldNotHaveReceived('warning'); +}); + +it('names only the servers a host policy allows guests', function (): void { + guestToolsWarningOnTheWeb(); + guestToolsWarningPolicy(PartialUpdateToolsMcpInstructionPolicy::class); + Log::spy(); + + runGuestToolsWarning(); + + Log::shouldHaveReceived('warning')->once()->withArgs( + fn (string $message, array $context): bool => str_contains($message, 'updateTools') + && $context === ['servers' => [PartialUpdateToolsMcpInstructionPolicy::ALLOWED_SERVER]], + ); +}); + +it('never names the cortex server', function (): void { + guestToolsWarningOnTheWeb(); + app(McpServerRegistry::class)->register('cortex-copy', CortexServer::class); + Log::spy(); + + runGuestToolsWarning(); + + Log::shouldHaveReceived('warning')->once()->withArgs( + fn (string $message, array $context): bool => $context === ['servers' => ['echo', 'plain', 'cortex-copy']], + ); +}); + +it('checks once per process', function (): void { + guestToolsWarningOnTheWeb(); + Log::spy(); + + runGuestToolsWarning(); + runGuestToolsWarning(); + + Log::shouldHaveReceived('warning')->once(); + + GuestToolsWarning::reset(); + runGuestToolsWarning(); + + Log::shouldHaveReceived('warning')->twice(); +}); diff --git a/tests/Fixtures/Policies/NoUpdateToolsMcpInstructionPolicy.php b/tests/Fixtures/Policies/NoUpdateToolsMcpInstructionPolicy.php new file mode 100644 index 0000000..bf42bcf --- /dev/null +++ b/tests/Fixtures/Policies/NoUpdateToolsMcpInstructionPolicy.php @@ -0,0 +1,41 @@ +server === self::ALLOWED_SERVER; + } +} diff --git a/tests/Support/FileDatabaseMigrations.php b/tests/Support/FileDatabaseMigrations.php new file mode 100644 index 0000000..2d47fb3 --- /dev/null +++ b/tests/Support/FileDatabaseMigrations.php @@ -0,0 +1,66 @@ +databaseFile = (string) tempnam(sys_get_temp_dir(), 'cortex-test-db-'); + + $app['config']->set('database.connections.testing', [ + 'driver' => 'sqlite', + 'database' => $this->databaseFile, + 'prefix' => '', + 'foreign_key_constraints' => true, + ]); + } + + /** + * The package migrations run through `migrate:fresh` (and roll back + * through `migrate:rollback`) instead of Testbench's loader. + */ + protected function defineDatabaseMigrations(): void + { + $this->app['migrator']->path(dirname(__DIR__, 2).'/database/migrations'); + } + + public function runDatabaseMigrations(): void + { + $file = $this->databaseFile; + + // Testbench runs these callbacks last registered first, so this one, + // registered before the rollback, runs once the tables are gone. + $this->beforeApplicationDestroyed(function () use ($file): void { + DB::disconnect(); + + if ($file !== null && is_file($file)) { + unlink($file); + } + }); + + $this->runLaravelDatabaseMigrations(); + } +} From 3f708e53e146830b2b585c306ce4c061544a83c9 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:19:54 -0400 Subject: [PATCH 09/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 5 Serving the overridden tool list Co-Authored-By: Claude Opus 5.5 (1M context) --- .../Concerns/HasCortexOverrides.php | 86 ++++ .../Concerns/HasVersionedInstructions.php | 31 +- .../ConcreteServerServiceProvider.php | 4 + .../Services/ServerContextMemo.php | 36 ++ .../Services/ServerContextRebuilder.php | 62 +++ .../Services/ServerToolResolver.php | 213 +++++++++ src/Domains/ConcreteServer/Support/Server.php | 16 +- src/Support/AiToolAsMcpTool.php | 77 ++++ .../Compat/OldNamespaceToolOverrideTest.php | 53 +++ tests/Feature/Mcp/ServerContextPinTest.php | 128 ++++++ tests/Feature/Mcp/ServerToolOverrideTest.php | 286 ++++++++++++ .../Mcp/ServerToolOverrideWarningsTest.php | 414 ++++++++++++++++++ tests/Fixtures/CollidingCortexTool.php | 35 ++ tests/Fixtures/ConstructorToolsServer.php | 39 ++ tests/Fixtures/GatedAiTool.php | 60 +++ tests/Fixtures/HiddenMcpTool.php | 34 ++ tests/Fixtures/ThrowingCortexTool.php | 35 ++ tests/Support/ServerContextTools.php | 68 +++ 18 files changed, 1645 insertions(+), 32 deletions(-) create mode 100644 src/Domains/ConcreteServer/Concerns/HasCortexOverrides.php create mode 100644 src/Domains/ConcreteServer/Services/ServerContextMemo.php create mode 100644 src/Domains/ConcreteServer/Services/ServerContextRebuilder.php create mode 100644 src/Domains/ConcreteServer/Services/ServerToolResolver.php create mode 100644 src/Support/AiToolAsMcpTool.php create mode 100644 tests/Feature/Compat/OldNamespaceToolOverrideTest.php create mode 100644 tests/Feature/Mcp/ServerContextPinTest.php create mode 100644 tests/Feature/Mcp/ServerToolOverrideTest.php create mode 100644 tests/Feature/Mcp/ServerToolOverrideWarningsTest.php create mode 100644 tests/Fixtures/CollidingCortexTool.php create mode 100644 tests/Fixtures/ConstructorToolsServer.php create mode 100644 tests/Fixtures/GatedAiTool.php create mode 100644 tests/Fixtures/HiddenMcpTool.php create mode 100644 tests/Fixtures/ThrowingCortexTool.php create mode 100644 tests/Support/ServerContextTools.php diff --git a/src/Domains/ConcreteServer/Concerns/HasCortexOverrides.php b/src/Domains/ConcreteServer/Concerns/HasCortexOverrides.php new file mode 100644 index 0000000..3cd210d --- /dev/null +++ b/src/Domains/ConcreteServer/Concerns/HasCortexOverrides.php @@ -0,0 +1,86 @@ +nameFor(static::class); + + if ($name === null) { + return parent::createContext(); + } + + return app(ServerContextMemo::class)->remember(static::class, function () use ($servers, $name): ServerContext { + $context = parent::createContext(); + + $instructions = app(McpInstructionOverrides::class)->for($name); + + if ($instructions !== null) { + // ServerContext::$instructions is a public non-readonly property + // in laravel/mcp; recheck this assignment on vendor upgrades. + $context->instructions = $instructions; + } + + $tools = $servers->supportsToolOverrides($name) ? app(McpToolOverrides::class)->for($name) : null; + + if ($tools === null) { + return $context; + } + + try { + $rebuilder = app(ServerContextRebuilder::class); + + return $rebuilder->withTools( + $context, + app(ServerToolResolver::class)->serve($name, $rebuilder->tools($context), $tools), + ); + } catch (Throwable $exception) { + app(WarningLimiter::class)->warn( + $name, + 'rebuild:'.$exception::class, + sprintf( + 'Cortex serves the code tools of MCP server [%s]: applying its tool override failed with %s.', + $name, + $exception::class, + ), + ['server' => $name, 'message' => $exception->getMessage()], + ); + + return $context; + } + }); + } +} diff --git a/src/Domains/ConcreteServer/Concerns/HasVersionedInstructions.php b/src/Domains/ConcreteServer/Concerns/HasVersionedInstructions.php index 68b33a1..a64f95a 100644 --- a/src/Domains/ConcreteServer/Concerns/HasVersionedInstructions.php +++ b/src/Domains/ConcreteServer/Concerns/HasVersionedInstructions.php @@ -4,35 +4,12 @@ namespace RefactorCircus\Cortex\Domains\ConcreteServer\Concerns; -use Laravel\Mcp\Server\ServerContext; -use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpInstructionOverrides; -use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; -use RefactorCircus\Cortex\Domains\ConcreteServer\Support\Server; - /** - * Serve the published Cortex instructions override, when one exists, in - * place of the code-declared instructions. Falls back to whatever the - * server declares in code (attribute or property) when no version is - * published or the server is not registered with Cortex. - * - * Use directly on servers that cannot extend {@see Server}. + * The trait's name from before it served tool overrides: it uses + * {@see HasCortexOverrides}, so servers using it get the published + * instructions override and the stored tool override alike. */ trait HasVersionedInstructions { - public function createContext(): ServerContext - { - $context = parent::createContext(); - - $name = app(McpServerRegistry::class)->nameFor(static::class); - - $override = $name === null ? null : app(McpInstructionOverrides::class)->for($name); - - if ($override !== null) { - // ServerContext::$instructions is a public non-readonly property - // in laravel/mcp; recheck this assignment on vendor upgrades. - $context->instructions = $override; - } - - return $context; - } + use HasCortexOverrides; } diff --git a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php index bf22e5b..7653935 100644 --- a/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php +++ b/src/Domains/ConcreteServer/ConcreteServerServiceProvider.php @@ -14,6 +14,7 @@ use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpInstructionOverrides; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpToolOverrides; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\ServerContextMemo; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\ToolsColumn; use RefactorCircus\Keystone\Support\ServiceProvider; use Throwable; @@ -59,6 +60,9 @@ public function register(): void $this->app->scoped(McpToolOverrides::class); + // A server's context is built once per request, never longer. + $this->app->scoped(ServerContextMemo::class); + // Checked once per process; a worker sees a newly run migration after // it restarts. $this->app->singleton(ToolsColumn::class); diff --git a/src/Domains/ConcreteServer/Services/ServerContextMemo.php b/src/Domains/ConcreteServer/Services/ServerContextMemo.php new file mode 100644 index 0000000..4b99367 --- /dev/null +++ b/src/Domains/ConcreteServer/Services/ServerContextMemo.php @@ -0,0 +1,36 @@ + + */ + private array $contexts = []; + + /** + * The context built for the server class in this request, building it + * on the first call. + * + * @param Closure(): ServerContext $build + */ + public function remember(string $server, Closure $build): ServerContext + { + return $this->contexts[$server] ??= $build(); + } +} diff --git a/src/Domains/ConcreteServer/Services/ServerContextRebuilder.php b/src/Domains/ConcreteServer/Services/ServerContextRebuilder.php new file mode 100644 index 0000000..cd4f88c --- /dev/null +++ b/src/Domains/ConcreteServer/Services/ServerContextRebuilder.php @@ -0,0 +1,62 @@ + + */ + public function tools(ServerContext $context): array + { + $tools = (new ReflectionProperty($context, 'tools'))->getValue($context); + + return is_array($tools) ? $tools : []; + } + + /** + * A copy of the context serving exactly these tools, in this order, with + * everything else (instructions, capabilities, resources, prompts) kept. + * + * @param list $tools + */ + public function withTools(ServerContext $context, array $tools): ServerContext + { + $class = new ReflectionClass($context); + $arguments = []; + + foreach ($class->getConstructor()?->getParameters() ?? [] as $parameter) { + $name = $parameter->getName(); + + $arguments[$name] = (new ReflectionProperty($context, $name))->getValue($context); + } + + // Passed by name whether or not the constructor still takes it: a + // constructor without `tools` fails here instead of serving the code + // tools silently. + $arguments['tools'] = $tools; + + /** @var ServerContext */ + return $class->newInstanceArgs($arguments); + } +} diff --git a/src/Domains/ConcreteServer/Services/ServerToolResolver.php b/src/Domains/ConcreteServer/Services/ServerToolResolver.php new file mode 100644 index 0000000..3152b53 --- /dev/null +++ b/src/Domains/ConcreteServer/Services/ServerToolResolver.php @@ -0,0 +1,213 @@ + $codeTools the context's tools as declared + * @param list $entries + * @return list + */ + public function serve(string $server, array $codeTools, array $entries): array + { + $resolved = $this->resolve($codeTools, $entries); + + foreach ($resolved['ambiguous'] as $entry) { + $this->warnings->warn( + $server, + 'ambiguous:'.$entry, + sprintf( + 'Cortex serves the code tool [%s] of MCP server [%s]: the tool override entry also names a registered Cortex tool, and the code tool wins.', + $entry, + $server, + ), + ['server' => $server, 'entry' => $entry], + ); + } + + foreach ($resolved['missing'] as $entry) { + if (array_key_exists($entry, $resolved['failed'])) { + $this->warnings->warn( + $server, + 'failed:'.$entry, + sprintf( + 'Cortex skips the tool [%s] in the tool override of MCP server [%s]: building the tool failed.', + $entry, + $server, + ), + ['server' => $server, 'entry' => $entry, 'message' => $resolved['failed'][$entry]], + ); + + continue; + } + + $this->warnings->warn( + $server, + 'stale:'.$entry, + sprintf( + 'Cortex skips the tool [%s] in the tool override of MCP server [%s]: neither the server code nor the Cortex tool registry has a tool by that name.', + $entry, + $server, + ), + ['server' => $server, 'entry' => $entry], + ); + } + + return $resolved['tools']; + } + + /** + * What the stored entries resolve to, without logging: the tools to + * serve in stored order, the entries that resolve to nothing or whose + * tool threw (`missing`, in stored order), the message of each throw + * (`failed`) and the entries that name a code tool and a registered tool + * (`ambiguous`). + * + * @param array $codeTools the context's tools as declared + * @param list $entries + * @return array{tools: list, missing: list, failed: array, ambiguous: list} + */ + public function resolve(array $codeTools, array $entries): array + { + $code = $this->codeTools($codeTools); + $registered = $this->registeredClasses(); + + $tools = []; + $served = []; + $missing = []; + $failed = []; + $ambiguous = []; + + foreach ($entries as $entry) { + if (isset($code[$entry])) { + $tool = $code[$entry]; + + if (isset($registered[$entry])) { + $ambiguous[] = $entry; + } + } elseif (isset($registered[$entry])) { + try { + $tool = $this->registeredTool($entry, $registered[$entry]); + } catch (Throwable $exception) { + $missing[] = $entry; + $failed[$entry] = $exception->getMessage(); + + continue; + } + } else { + $missing[] = $entry; + + continue; + } + + // Validation keeps served names apart; a tool renamed since is + // served once. + if (isset($served[$tool->name()])) { + continue; + } + + $served[$tool->name()] = true; + $tools[] = $tool; + } + + return ['tools' => $tools, 'missing' => $missing, 'failed' => $failed, 'ambiguous' => $ambiguous]; + } + + /** + * The server's code tools by `name()`, the first of a name winning. + * ToolSearch groups are flattened; a class that cannot be built cannot + * be named, so no entry resolves to it. + * + * @param array $declared + * @return array + */ + private function codeTools(array $declared): array + { + $tools = []; + + foreach ($declared as $entry) { + foreach (is_array($entry) ? $entry : [$entry] as $tool) { + try { + $tool = is_string($tool) ? $this->container->make($tool) : $tool; + } catch (Throwable) { + continue; + } + + if ($tool instanceof Tool) { + $tools[$tool->name()] ??= $tool; + } + } + } + + return $tools; + } + + /** + * Every registered tool's class by registration name. + * + * @return array + */ + private function registeredClasses(): array + { + $classes = []; + + foreach ($this->registry->summaries() as $summary) { + $classes[$summary['name']] = $summary['class']; + } + + return $classes; + } + + /** + * @param class-string $class + */ + private function registeredTool(string $name, string $class): Tool + { + $tool = $this->container->make($class); + + if ($tool instanceof Tool) { + return $tool; + } + + /** @var AiTool $tool */ + return new AiToolAsMcpTool($tool, $this->descriptions->for($name)); + } +} diff --git a/src/Domains/ConcreteServer/Support/Server.php b/src/Domains/ConcreteServer/Support/Server.php index 38c1015..3a23b62 100644 --- a/src/Domains/ConcreteServer/Support/Server.php +++ b/src/Domains/ConcreteServer/Support/Server.php @@ -5,14 +5,20 @@ namespace RefactorCircus\Cortex\Domains\ConcreteServer\Support; use Laravel\Mcp\Server as McpServer; +use RefactorCircus\Cortex\Domains\ConcreteServer\Concerns\HasCortexOverrides; use RefactorCircus\Cortex\Domains\ConcreteServer\Concerns\HasVersionedInstructions; /** - * Base class for MCP servers whose instructions Cortex manages: register the - * class with the McpServerRegistry (built in for Cortex's own server, via - * the `cortex.mcp.servers` config, or at runtime) and the instructions - * served to clients are the published Cortex version when one exists, - * falling back to the code-declared instructions otherwise. + * Base class for MCP servers that Cortex manages: register the class with + * the McpServerRegistry (built in for Cortex's own server, via the + * `cortex.mcp.servers` config, or at runtime) and clients are served the + * published Cortex instructions when a version exists, and the stored tool + * override when one is saved, falling back to what the class declares in + * code otherwise. + * + * It uses the trait by its kept name, which brings in + * {@see HasCortexOverrides}, so the base class and the servers that use + * either trait serve the same overrides. */ abstract class Server extends McpServer { diff --git a/src/Support/AiToolAsMcpTool.php b/src/Support/AiToolAsMcpTool.php new file mode 100644 index 0000000..95e1cac --- /dev/null +++ b/src/Support/AiToolAsMcpTool.php @@ -0,0 +1,77 @@ +tool; + } + + public function name(): string + { + return ToolNameResolver::resolve($this->tool); + } + + public function title(): string + { + return Str::headline($this->name()); + } + + public function description(): string + { + return $this->publishedDescription ?? (string) $this->tool->description(); + } + + /** + * @return array + */ + public function schema(JsonSchema $schema): array + { + return $this->tool->schema($schema); + } + + public function shouldRegister(): bool + { + if (! method_exists($this->tool, 'shouldRegister')) { + return true; + } + + return (bool) Container::getInstance()->call([$this->tool, 'shouldRegister']); + } + + public function handle(Request $request): Response + { + return Response::text((string) $this->tool->handle(new AiRequest($request->all()))); + } +} diff --git a/tests/Feature/Compat/OldNamespaceToolOverrideTest.php b/tests/Feature/Compat/OldNamespaceToolOverrideTest.php new file mode 100644 index 0000000..730ffa2 --- /dev/null +++ b/tests/Feature/Compat/OldNamespaceToolOverrideTest.php @@ -0,0 +1,53 @@ +flush(); + + app(McpServerRegistry::class)->register('old-namespace', OldNamespaceServer::class); + app(McpServerRegistry::class)->register('old-trait', OldTraitServer::class); + + app(ToolRegistry::class)->register('echo-mcp-tool', EchoMcpTool::class); + app(ToolRegistry::class)->register('echo-cortex-tool', EchoCortexTool::class); +}); + +it('serves a saved tool override and its code tools again once it is cleared', function (string $server, string $class): void { + // Neither fixture declares tools. + expect(ServerContextTools::listed($class::tools()))->toBe([]); + + app(UpdateConcreteServerToolsAction::class)->execute($server, UpdateConcreteServerToolsData::from([ + 'tools' => ['echo-cortex-tool', 'echo-mcp-tool'], + ], $server)); + app()->forgetScopedInstances(); + + expect(ServerContextTools::listed($class::tools()))->toBe(['echo-cortex-tool', 'echo-mcp-tool']); + + $class::tool(EchoMcpTool::class, ['message' => 'old host'])->assertOk()->assertSee('old host'); + + app(ClearConcreteServerToolsAction::class)->execute($server, ClearConcreteServerToolsData::from([], $server)); + app()->forgetScopedInstances(); + + expect(ServerContextTools::listed($class::tools()))->toBe([]); +})->with([ + 'old base class' => ['old-namespace', OldNamespaceServer::class], + 'old trait name' => ['old-trait', OldTraitServer::class], +]); diff --git a/tests/Feature/Mcp/ServerContextPinTest.php b/tests/Feature/Mcp/ServerContextPinTest.php new file mode 100644 index 0000000..8972300 --- /dev/null +++ b/tests/Feature/Mcp/ServerContextPinTest.php @@ -0,0 +1,128 @@ + + */ +function pinnedListedNames(ServerContext $context): array +{ + $response = (new ListTools)->handle(new JsonRpcRequest(1, 'tools/list', []), $context); + + /** @var list */ + return array_column($response->toArray()['result']['tools'], 'name'); +} + +it('pins the ServerContext constructor the rebuild passes, each parameter backed by its property', function (): void { + $parameters = (new ReflectionMethod(ServerContext::class, '__construct'))->getParameters(); + + expect(array_map(fn (ReflectionParameter $parameter): string => $parameter->getName(), $parameters))->toBe([ + 'supportedProtocolVersions', + 'serverCapabilities', + 'implementation', + 'instructions', + 'maxPaginationLength', + 'defaultPaginationLength', + 'tools', + 'resources', + 'prompts', + ]); + + foreach ($parameters as $parameter) { + expect($parameter->isPromoted())->toBeTrue("[{$parameter->getName()}] is no longer a promoted property.") + ->and($parameter->isOptional())->toBeFalse(); + } +}); + +it('pins the protected tools property the rebuild reads', function (): void { + $property = new ReflectionProperty(ServerContext::class, 'tools'); + + expect($property->isProtected())->toBeTrue() + ->and($property->isReadOnly())->toBeFalse() + ->and((string) $property->getType())->toBe('array') + // The instructions override assigns this one directly. + ->and((new ReflectionProperty(ServerContext::class, 'instructions'))->isPublic())->toBeTrue() + ->and((new ReflectionProperty(ServerContext::class, 'instructions'))->isReadOnly())->toBeFalse(); +}); + +it('keeps the order of the context tools in tools/list', function (array $tools, array $names): void { + $context = (new EchoServer(new FakeTransporter))->createContext(); + + $rebuilt = app(ServerContextRebuilder::class)->withTools($context, array_map(fn (string $class): Tool => app($class), $tools)); + + expect(ServerContextTools::names($rebuilt))->toBe($names) + ->and(pinnedListedNames($rebuilt))->toBe($names); +})->with([ + 'declared order' => [[NamedMcpTool::class, EchoMcpTool::class, EchoRequestTool::class], ['renamed-echo', 'echo-mcp-tool', 'echo-request-tool']], + 'reversed' => [[EchoRequestTool::class, EchoMcpTool::class, NamedMcpTool::class], ['echo-request-tool', 'echo-mcp-tool', 'renamed-echo']], +]); + +it('reads the tools a context was built with through the shared helper', function (): void { + $context = (new GroupedToolsServer(new FakeTransporter))->createContext(); + + expect(ServerContextTools::of($context))->toBe([ + EchoMcpTool::class, + ToolSearch::class => [EchoRequestTool::class, NamedMcpTool::class], + ]) + ->and(ServerContextTools::of($context))->toBe(app(ServerContextRebuilder::class)->tools($context)); +}); + +it('rebuilds a context from a real server that keeps everything but its tools and serves it end to end', function (): void { + $context = (new GroupedToolsServer(new FakeTransporter))->createContext(); + $context->instructions = 'Rebuilt instructions.'; + + $rebuilt = app(ServerContextRebuilder::class)->withTools($context, [app(NamedMcpTool::class)]); + + expect($rebuilt)->not->toBe($context) + ->and($rebuilt->instructions)->toBe('Rebuilt instructions.') + ->and($rebuilt->implementation)->toBe($context->implementation) + ->and($rebuilt->supportedProtocolVersions)->toBe($context->supportedProtocolVersions) + ->and($rebuilt->serverCapabilities)->toBe($context->serverCapabilities) + ->and($rebuilt->maxPaginationLength)->toBe($context->maxPaginationLength) + ->and($rebuilt->defaultPaginationLength)->toBe($context->defaultPaginationLength) + ->and($rebuilt->resources()->all())->toBe($context->resources()->all()) + ->and($rebuilt->prompts()->all())->toBe($context->prompts()->all()) + ->and(pinnedListedNames($rebuilt))->toBe(['renamed-echo']) + // The source context is left as it was. + ->and(pinnedListedNames($context))->toBe(['echo-mcp-tool', 'search_tools', 'execute_tools']); + + $call = new JsonRpcRequest(2, 'tools/call', [ + 'name' => 'renamed-echo', + 'arguments' => ['message' => 'pinned'], + ]); + + // As Server::runMethodHandle() does around every method. + app()->instance('mcp.request', $call->toRequest()); + + try { + $called = (new CallTool)->handle($call, $rebuilt); + } finally { + app()->forgetInstance('mcp.request'); + } + + expect($called)->toBeInstanceOf(JsonRpcResponse::class) + ->and($called->toArray()['result']['content'][0]['text'])->toBe('pinned'); +}); diff --git a/tests/Feature/Mcp/ServerToolOverrideTest.php b/tests/Feature/Mcp/ServerToolOverrideTest.php new file mode 100644 index 0000000..29e0c6f --- /dev/null +++ b/tests/Feature/Mcp/ServerToolOverrideTest.php @@ -0,0 +1,286 @@ +flush(); + GatedAiTool::reset(); + + app(McpServerRegistry::class)->register('grouped', GroupedToolsServer::class); + app(McpServerRegistry::class)->register('constructor', ConstructorToolsServer::class); + + app(ToolRegistry::class)->register('echo-cortex-tool', EchoCortexTool::class); +}); + +/** + * Save a server's tool override through the update action, then start a new + * request. + * + * @param list|null $tools + */ +function saveOverriddenTools(string $server, ?array $tools): void +{ + app(UpdateConcreteServerToolsAction::class)->execute($server, UpdateConcreteServerToolsData::from(['tools' => $tools], $server)); + + app()->forgetScopedInstances(); +} + +/** + * Write a server's override row directly, for lists the update action would + * refuse (tools a server adds at runtime), then start a new request. + * + * @param list|null $tools + */ +function writeOverriddenTools(string $server, ?array $tools, ?string $published = null): McpInstructionModel +{ + $instruction = McpInstructionModel::query()->updateOrCreate(['server' => $server], ['tools' => $tools]); + + if ($published !== null) { + $version = $instruction->versions()->create(['version' => 1, 'content' => $published]); + $instruction->published_version_id = $version->getKey(); + $instruction->save(); + } + + $cache = app(PublicationCache::class); + $cache->forget($cache->mcpToolsKey(), $cache->mcpInstructionsKey()); + + app()->forgetScopedInstances(); + + return $instruction; +} + +describe('the served list', function (): void { + it('lists exactly the stored tools, code tools by name and registered tools from the registry', function (): void { + saveOverriddenTools('grouped', ['renamed-echo', 'echo-cortex-tool']); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['renamed-echo', 'echo-cortex-tool']); + + GroupedToolsServer::tool(NamedMcpTool::class, ['message' => 'code tool'])->assertOk()->assertSee('code tool'); + GroupedToolsServer::tool(EchoCortexTool::class, ['message' => 'registered tool'])->assertOk()->assertSee('registered tool'); + }); + + it('lists the code tools without a row, with a null list and with an instructions-only row', function (?Closure $row): void { + $row?->__invoke(); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool', 'search_tools', 'execute_tools']); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'still here'])->assertOk()->assertSee('still here'); + })->with([ + 'no row' => [null], + 'null list' => [fn () => fn () => writeOverriddenTools('grouped', null)], + 'null list saved through the action' => [fn () => fn () => saveOverriddenTools('grouped', null)], + 'instructions only' => [fn () => fn () => writeOverriddenTools('grouped', null, 'Published grouped instructions.')], + ]); + + it('fails a call to a tool the override removed, naming the tool', function (): void { + saveOverriddenTools('grouped', ['renamed-echo']); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'gone']) + ->assertHasErrors(['Tool [echo-mcp-tool] not found.']); + }); + + it('serves no tools for an empty list', function (): void { + saveOverriddenTools('grouped', []); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe([]); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'gone']) + ->assertHasErrors(['Tool [echo-mcp-tool] not found.']); + }); + + it('serves a tool-only row, which has no published instructions', function (): void { + $instruction = writeOverriddenTools('grouped', ['echo-mcp-tool']); + + expect($instruction->fresh()?->published_version_id)->toBeNull() + ->and($instruction->versions()->count())->toBe(0) + ->and(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool']) + ->and((new GroupedToolsServer(new FakeTransporter))->createContext()->instructions)->toBe('Grouped tools server instructions.'); + }); + + it('serves the tool override together with the published instructions', function (): void { + writeOverriddenTools('grouped', ['renamed-echo'], 'Published grouped instructions.'); + + $context = (new GroupedToolsServer(new FakeTransporter))->createContext(); + + expect($context->instructions)->toBe('Published grouped instructions.') + ->and(ServerContextTools::names($context))->toBe(['renamed-echo']); + }); +}); + +describe('order (AC 10a)', function (): void { + it('builds the context and the client list in stored order', function (array $stored): void { + saveOverriddenTools('grouped', $stored); + + expect(ServerContextTools::names((new GroupedToolsServer(new FakeTransporter))->createContext()))->toBe($stored) + ->and(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe($stored); + })->with([ + 'registered first' => [['echo-cortex-tool', 'renamed-echo', 'echo-mcp-tool', 'echo-request-tool']], + 'reversed' => [['echo-request-tool', 'echo-mcp-tool', 'renamed-echo', 'echo-cortex-tool']], + ]); +}); + +describe('code tools', function (): void { + it('serves a ToolSearch server as a flat list when overridden (AC 10b)', function (): void { + saveOverriddenTools('grouped', ['echo-request-tool', 'echo-mcp-tool', 'renamed-echo']); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-request-tool', 'echo-mcp-tool', 'renamed-echo']); + + // A grouped tool is called directly, not through execute_tools. + GroupedToolsServer::tool(EchoRequestTool::class, ['message' => 'flat'])->assertOk()->assertSee('flat'); + }); + + it('selects tools a host adds in its constructor or boot() (AC 10c)', function (): void { + // Without an override the runtime tools are served as code tools. + expect(ServerContextTools::listed(ConstructorToolsServer::tools()))->toBe(['echo-mcp-tool', 'renamed-echo', 'echo-request-tool']); + + writeOverriddenTools('constructor', ['echo-request-tool', 'renamed-echo']); + + expect(ServerContextTools::listed(ConstructorToolsServer::tools()))->toBe(['echo-request-tool', 'renamed-echo']); + + ConstructorToolsServer::tool(EchoRequestTool::class, ['message' => 'from boot'])->assertOk()->assertSee('from boot'); + ConstructorToolsServer::tool(NamedMcpTool::class, ['message' => 'from the constructor'])->assertOk()->assertSee('from the constructor'); + }); +}); + +describe('tool visibility (AC 10e)', function (): void { + it('keeps a selected code tool hidden when it does not register', function (): void { + writeOverriddenTools('constructor', ['hidden-mcp-tool', 'echo-mcp-tool']); + + expect(ServerContextTools::listed(ConstructorToolsServer::tools()))->toBe(['echo-mcp-tool']); + + ConstructorToolsServer::tool(HiddenMcpTool::class)->assertHasErrors(['Tool [hidden-mcp-tool] not found.']); + }); + + it('keeps a selected registered tool hidden when it does not register', function (): void { + app(ToolRegistry::class)->register('hidden-mcp-tool', HiddenMcpTool::class); + + saveOverriddenTools('grouped', ['hidden-mcp-tool', 'echo-mcp-tool']); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool']); + + GroupedToolsServer::tool(HiddenMcpTool::class)->assertHasErrors(['Tool [hidden-mcp-tool] not found.']); + }); + + it('keeps the own gating of a Laravel AI tool and lets the request user reach it', function (): void { + app(ToolRegistry::class)->register('gated-ai-tool', GatedAiTool::class); + + saveOverriddenTools('grouped', ['gated-ai-tool', 'echo-mcp-tool']); + + $gated = new AiToolAsMcpTool(new GatedAiTool); + + // A guest: the tool's own check refuses it. + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool']) + ->and(GatedAiTool::$asked)->toBeTrue() + ->and(GatedAiTool::$seenUser)->toBeNull(); + + GroupedToolsServer::tool($gated, ['message' => 'guest'])->assertHasErrors(['Tool [gated-ai-tool] not found.']); + + // A signed-in user: the same check sees them and serves the tool. + GatedAiTool::reset(); + $user = new GenericUser(['id' => 7]); + + expect(ServerContextTools::listed(GroupedToolsServer::actingAs($user)->tools()))->toBe(['gated-ai-tool', 'echo-mcp-tool']) + ->and(GatedAiTool::$seenUser?->getAuthIdentifier())->toBe(7); + + GroupedToolsServer::actingAs($user)->tool($gated, ['message' => 'signed in'])->assertOk()->assertSee('gated: signed in'); + }); +}); + +describe('per-request memo (AC 10d, 10f)', function (): void { + it('builds the context once per request', function (): void { + saveOverriddenTools('grouped', ['renamed-echo']); + + $first = (new GroupedToolsServer(new FakeTransporter))->createContext(); + + expect((new GroupedToolsServer(new FakeTransporter))->createContext())->toBe($first); + + app()->forgetScopedInstances(); + + expect((new GroupedToolsServer(new FakeTransporter))->createContext())->not->toBe($first); + }); + + it('is scoped to the request, so the next request in the same process serves a new list', function (): void { + saveOverriddenTools('grouped', ['renamed-echo']); + + $memo = app(ServerContextMemo::class); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['renamed-echo']); + + // A change made in the same container (Octane, repeated client calls) ... + app(UpdateConcreteServerToolsAction::class)->execute('grouped', UpdateConcreteServerToolsData::from(['tools' => ['echo-mcp-tool', 'renamed-echo']], 'grouped')); + + // ... is served from the next request on. + app()->forgetScopedInstances(); + + expect(app(ServerContextMemo::class))->not->toBe($memo) + ->and(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool', 'renamed-echo']); + }); +}); + +describe('servers that are not overridable (AC 12)', function (): void { + it('ignores a cortex row with tools on the registered cortex route', function (): void { + writeOverriddenTools('cortex', ['list-tools-tool']); + + config()->set('cortex.mcp.web.enabled', true); + (new CortexServiceProvider(app()))->boot(); + + $route = (string) config('cortex.mcp.web.route'); + + expect(Mcp::getWebServer($route))->not->toBeNull(); + + $response = $this->postJson('/'.ltrim($route, '/'), ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/list']) + ->assertOk(); + + expect(array_column($response->json('result.tools'), 'name'))->toBe(['search_tools', 'execute_tools']) + ->and(ServerContextTools::listed(CortexServer::tools()))->toBe(['search_tools', 'execute_tools']); + }); + + it('ignores a tools row for any server registered under the cortex name', function (): void { + // EchoServer declares no tools, so an applied row would show. + app(McpServerRegistry::class)->register('cortex', EchoServer::class); + + writeOverriddenTools('cortex', ['echo-cortex-tool']); + + expect(app(McpServerRegistry::class)->nameFor(EchoServer::class))->toBe('cortex') + ->and(ServerContextTools::listed(EchoServer::tools()))->toBe([]); + }); + + it('serves its code tools for a server not registered with Cortex', function (): void { + writeOverriddenTools('echo-server', ['echo-mcp-tool']); + + expect(ServerContextTools::listed(EchoServer::tools()))->toBe([]); + }); +}); + +it('serves the tool override through the base class and both trait names', function (): void { + expect(class_uses_recursive(Server::class))->toContain(HasCortexOverrides::class) + ->and(class_uses(HasVersionedInstructions::class))->toBe([HasCortexOverrides::class => HasCortexOverrides::class]); +}); diff --git a/tests/Feature/Mcp/ServerToolOverrideWarningsTest.php b/tests/Feature/Mcp/ServerToolOverrideWarningsTest.php new file mode 100644 index 0000000..7c9f71b --- /dev/null +++ b/tests/Feature/Mcp/ServerToolOverrideWarningsTest.php @@ -0,0 +1,414 @@ +flush(); + + app(McpServerRegistry::class)->register('grouped', GroupedToolsServer::class); +}); + +/** + * Write the grouped server's override row directly (stale entries cannot be + * saved through the update action), then start a new request. + * + * @param list $tools + */ +function writeGroupedTools(array $tools, ?string $published = null): void +{ + $instruction = McpInstructionModel::query()->updateOrCreate(['server' => 'grouped'], ['tools' => $tools]); + + if ($published !== null) { + $version = $instruction->versions()->create(['version' => 1, 'content' => $published]); + $instruction->published_version_id = $version->getKey(); + $instruction->save(); + } + + $cache = app(PublicationCache::class); + $cache->forget($cache->mcpToolsKey(), $cache->mcpInstructionsKey()); + + app()->forgetScopedInstances(); +} + +/** + * Start a new request in the same process. + */ +function nextGroupedRequest(): void +{ + app()->forgetScopedInstances(); +} + +/** + * @param array $context + */ +function assertWarnedOnce(array $context, ?string $messagePart = null): void +{ + // The argument filter comes first: Mockery checks the count as soon as + // it is chained. + Log::shouldHaveReceived('warning')->withArgs( + fn (string $message, array $logged = []): bool => $logged === $context + && ($messagePart === null || str_contains($message, $messagePart)), + )->once(); +} + +describe('stale and failing entries (AC 16)', function (): void { + it('skips an entry that no longer resolves, logs it and serves the rest', function (): void { + Log::spy(); + + writeGroupedTools(['echo-mcp-tool', 'gone-tool']); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool']); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'kept'])->assertOk()->assertSee('kept'); + + assertWarnedOnce(['server' => 'grouped', 'entry' => 'gone-tool'], 'gone-tool'); + Log::shouldHaveReceived('warning')->once(); + + // The silent report names it for the resource (no warning of its own). + $report = app(ServerToolResolver::class)->resolve( + app(ServerContextRebuilder::class)->tools((new GroupedToolsServer(new FakeTransporter))->createContext()), + ['echo-mcp-tool', 'gone-tool'], + ); + + expect($report['missing'])->toBe(['gone-tool']); + Log::shouldHaveReceived('warning')->once(); + }); + + it('skips an entry whose tool throws while built, logs the message and serves the rest', function (): void { + app(ToolRegistry::class)->register('throwing-cortex-tool', ThrowingCortexTool::class); + + app(UpdateConcreteServerToolsAction::class)->execute('grouped', UpdateConcreteServerToolsData::from([ + 'tools' => ['throwing-cortex-tool', 'echo-mcp-tool', 'renamed-echo'], + ], 'grouped')); + nextGroupedRequest(); + + Log::spy(); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool', 'renamed-echo']); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'one'])->assertOk()->assertSee('one'); + GroupedToolsServer::tool(NamedMcpTool::class, ['message' => 'two'])->assertOk()->assertSee('two'); + + assertWarnedOnce(['server' => 'grouped', 'entry' => 'throwing-cortex-tool', 'message' => ThrowingCortexTool::MESSAGE]); + Log::shouldHaveReceived('warning')->once(); + + $report = app(ServerToolResolver::class)->resolve( + app(ServerContextRebuilder::class)->tools((new GroupedToolsServer(new FakeTransporter))->createContext()), + ['throwing-cortex-tool', 'echo-mcp-tool'], + ); + + expect($report['missing'])->toBe(['throwing-cortex-tool']) + ->and($report['failed'])->toBe(['throwing-cortex-tool' => ThrowingCortexTool::MESSAGE]); + }); + + it('rate-limits a stale entry across requests until the window passes', function (): void { + config()->set('cortex.mcp.warning_ttl', 120); + Log::spy(); + + writeGroupedTools(['gone-tool']); + + GroupedToolsServer::tools(); + nextGroupedRequest(); + GroupedToolsServer::tools(); + + Log::shouldHaveReceived('warning')->once(); + + $this->travel((int) config('cortex.mcp.warning_ttl') + 1)->seconds(); + nextGroupedRequest(); + GroupedToolsServer::tools(); + + Log::shouldHaveReceived('warning')->withArgs( + fn (string $message, array $context = []): bool => $context === ['server' => 'grouped', 'entry' => 'gone-tool'], + )->twice(); + }); + + it('limits different entries on the same server independently', function (): void { + Log::spy(); + + writeGroupedTools(['gone-a']); + GroupedToolsServer::tools(); + + writeGroupedTools(['gone-a', 'gone-b']); + GroupedToolsServer::tools(); + + assertWarnedOnce(['server' => 'grouped', 'entry' => 'gone-a']); + assertWarnedOnce(['server' => 'grouped', 'entry' => 'gone-b']); + Log::shouldHaveReceived('warning')->twice(); + }); + + it('serves and warns when the cache store throws', function (): void { + $store = new class implements Store + { + /** + * @var list + */ + public array $calls = []; + + public function add(string $key, mixed $value, int $seconds): bool + { + return $this->fail(__FUNCTION__); + } + + public function get($key) + { + return $this->fail(__FUNCTION__); + } + + public function many(array $keys) + { + return $this->fail(__FUNCTION__); + } + + public function put($key, $value, $seconds) + { + return $this->fail(__FUNCTION__); + } + + public function putMany(array $values, $seconds) + { + return $this->fail(__FUNCTION__); + } + + public function increment($key, $value = 1) + { + return $this->fail(__FUNCTION__); + } + + public function decrement($key, $value = 1) + { + return $this->fail(__FUNCTION__); + } + + public function forever($key, $value) + { + return $this->fail(__FUNCTION__); + } + + public function touch($key, $seconds) + { + return $this->fail(__FUNCTION__); + } + + public function forget($key) + { + return $this->fail(__FUNCTION__); + } + + public function flush() + { + return $this->fail(__FUNCTION__); + } + + public function getPrefix() + { + return ''; + } + + private function fail(string $call): never + { + $this->calls[] = $call; + + throw new RuntimeException('Cache store is down.'); + } + }; + + writeGroupedTools(['echo-mcp-tool', 'gone-tool']); + + Cache::extend('throwing', fn () => Cache::repository($store)); + config()->set('cache.stores.throwing', ['driver' => 'throwing']); + config()->set('cortex.cache.store', 'throwing'); + nextGroupedRequest(); + + Log::spy(); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool']) + ->and($store->calls)->toContain('add'); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'still served'])->assertOk()->assertSee('still served'); + + assertWarnedOnce(['server' => 'grouped', 'entry' => 'gone-tool']); + }); +}); + +describe('ambiguous entries (AC 10d)', function (): void { + it('serves the code tool for an entry that also names a registered tool, and logs it', function (): void { + app(UpdateConcreteServerToolsAction::class)->execute('grouped', UpdateConcreteServerToolsData::from([ + 'tools' => ['echo-mcp-tool', 'renamed-echo'], + ], 'grouped')); + + // Registered after the override was saved. + app(ToolRegistry::class)->register('echo-mcp-tool', CollidingCortexTool::class); + nextGroupedRequest(); + + Log::spy(); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool', 'renamed-echo']); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'code wins']) + ->assertOk() + ->assertSee('code wins') + ->assertDontSee(CollidingCortexTool::ANSWER); + + assertWarnedOnce(['server' => 'grouped', 'entry' => 'echo-mcp-tool'], 'echo-mcp-tool'); + Log::shouldHaveReceived('warning')->once(); + + $report = app(ServerToolResolver::class)->resolve( + app(ServerContextRebuilder::class)->tools((new GroupedToolsServer(new FakeTransporter))->createContext()), + ['echo-mcp-tool', 'renamed-echo'], + ); + + expect($report['ambiguous'])->toBe(['echo-mcp-tool']) + ->and($report['missing'])->toBe([]); + Log::shouldHaveReceived('warning')->once(); + }); + + it('logs exactly one warning per ambiguous entry for one client request', function (): void { + writeGroupedTools(['echo-mcp-tool', 'renamed-echo', 'echo-request-tool']); + + app(ToolRegistry::class)->register('echo-mcp-tool', CollidingCortexTool::class); + app(ToolRegistry::class)->register('renamed-echo', CollidingCortexTool::class); + + Log::spy(); + + GroupedToolsServer::tools(); + + assertWarnedOnce(['server' => 'grouped', 'entry' => 'echo-mcp-tool']); + assertWarnedOnce(['server' => 'grouped', 'entry' => 'renamed-echo']); + Log::shouldHaveReceived('warning')->twice(); + }); + + it('does not repeat the warnings when the context is built twice in one request', function (): void { + writeGroupedTools(['echo-mcp-tool']); + app(ToolRegistry::class)->register('echo-mcp-tool', CollidingCortexTool::class); + + Log::spy(); + + $first = (new GroupedToolsServer(new FakeTransporter))->createContext(); + + // Even with the limiter's keys gone, the memo answers. + Cache::store('array')->flush(); + + expect((new GroupedToolsServer(new FakeTransporter))->createContext())->toBe($first); + + Log::shouldHaveReceived('warning')->once(); + + // The next request builds again; with the keys gone it warns again. + Cache::store('array')->flush(); + nextGroupedRequest(); + (new GroupedToolsServer(new FakeTransporter))->createContext(); + + Log::shouldHaveReceived('warning')->twice(); + }); +}); + +it('serves the code tools for a corrupt stored value and logs its type (AC 18)', function (): void { + DB::table(Tables::name('mcp_instructions'))->insert([ + 'id' => (string) Str::ulid(), + 'server' => 'grouped', + 'tools' => '"echo-mcp-tool"', + 'created_at' => now(), + 'updated_at' => now(), + ]); + + Log::spy(); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool', 'search_tools', 'execute_tools']); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'code'])->assertOk()->assertSee('code'); + + assertWarnedOnce(['server' => 'grouped', 'value_type' => 'string']); + Log::shouldHaveReceived('warning')->once(); +}); + +it('serves the code tools with the instructions override and warns once without the tools column (AC 8)', function (): void { + writeGroupedTools(['renamed-echo'], 'Published grouped instructions.'); + + Schema::table(Tables::name('mcp_instructions'), function (Blueprint $table): void { + $table->dropColumn('tools'); + }); + + app()->forgetInstance(ToolsColumn::class); + nextGroupedRequest(); + + Log::spy(); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool', 'search_tools', 'execute_tools']) + ->and((new GroupedToolsServer(new FakeTransporter))->createContext()->instructions)->toBe('Published grouped instructions.'); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'no column'])->assertOk()->assertSee('no column'); + + nextGroupedRequest(); + GroupedToolsServer::tools(); + + assertWarnedOnce(['server' => 'grouped'], 'add_tools_to_cortex_mcp_instructions'); + Log::shouldHaveReceived('warning')->once(); +}); + +describe('a failing context rebuild (D-028, D-047)', function (): void { + it('serves the code tools with the instructions override and logs the failure', function (): void { + writeGroupedTools(['renamed-echo'], 'Published grouped instructions.'); + + app()->bind(ServerContextRebuilder::class, fn () => throw new RuntimeException('The rebuild broke.')); + + Log::spy(); + + expect(ServerContextTools::listed(GroupedToolsServer::tools()))->toBe(['echo-mcp-tool', 'search_tools', 'execute_tools']) + ->and((new GroupedToolsServer(new FakeTransporter))->createContext()->instructions)->toBe('Published grouped instructions.'); + + GroupedToolsServer::tool(EchoMcpTool::class, ['message' => 'fallback'])->assertOk()->assertSee('fallback'); + + assertWarnedOnce(['server' => 'grouped', 'message' => 'The rebuild broke.'], RuntimeException::class); + Log::shouldHaveReceived('warning')->once(); + }); + + it('rate-limits the failure by server and exception class', function (): void { + writeGroupedTools(['renamed-echo']); + + app()->bind(ServerContextRebuilder::class, fn () => throw new RuntimeException('The rebuild broke.')); + + Log::spy(); + + GroupedToolsServer::tools(); + nextGroupedRequest(); + GroupedToolsServer::tools(); + + Log::shouldHaveReceived('warning')->once(); + + // Another exception class logs on its own. + app()->bind(ServerContextRebuilder::class, fn () => throw new LogicException('The rebuild broke differently.')); + nextGroupedRequest(); + GroupedToolsServer::tools(); + + assertWarnedOnce(['server' => 'grouped', 'message' => 'The rebuild broke differently.'], LogicException::class); + Log::shouldHaveReceived('warning')->twice(); + }); +}); diff --git a/tests/Fixtures/CollidingCortexTool.php b/tests/Fixtures/CollidingCortexTool.php new file mode 100644 index 0000000..68500d5 --- /dev/null +++ b/tests/Fixtures/CollidingCortexTool.php @@ -0,0 +1,35 @@ + $schema->string()->description('Ignored.'), + ]; + } +} diff --git a/tests/Fixtures/ConstructorToolsServer.php b/tests/Fixtures/ConstructorToolsServer.php new file mode 100644 index 0000000..28eaaa8 --- /dev/null +++ b/tests/Fixtures/ConstructorToolsServer.php @@ -0,0 +1,39 @@ +|Tool> + */ + protected array $tools = [ + EchoMcpTool::class, + HiddenMcpTool::class, + ]; + + public function __construct(Transport $transport) + { + parent::__construct($transport); + + $this->tools[] = NamedMcpTool::class; + } + + protected function boot(): void + { + $this->tools[] = new EchoRequestTool; + } +} diff --git a/tests/Fixtures/GatedAiTool.php b/tests/Fixtures/GatedAiTool.php new file mode 100644 index 0000000..00938a9 --- /dev/null +++ b/tests/Fixtures/GatedAiTool.php @@ -0,0 +1,60 @@ +user(); + + return self::$seenUser !== null; + } + + public function description(): Stringable|string + { + return 'Echoes back the given message to signed-in users.'; + } + + public function handle(Request $request): Stringable|string + { + return 'gated: '.$request->string('message'); + } + + public function schema(JsonSchema $schema): array + { + return [ + 'message' => $schema->string()->description('The message to echo.')->required(), + ]; + } +} diff --git a/tests/Fixtures/HiddenMcpTool.php b/tests/Fixtures/HiddenMcpTool.php new file mode 100644 index 0000000..651da82 --- /dev/null +++ b/tests/Fixtures/HiddenMcpTool.php @@ -0,0 +1,34 @@ + + */ + public static function of(ServerContext $context): array + { + /** @var array */ + return (new ReflectionProperty(ServerContext::class, 'tools'))->getValue($context); + } + + /** + * The `name()` of each tool the context was built with, in order. A + * class name is built through the container; a ToolSearch group is + * listed by its key. + * + * @return list + */ + public static function names(ServerContext $context): array + { + $names = []; + + foreach (self::of($context) as $key => $tool) { + if (is_array($tool)) { + $names[] = (string) $key; + + continue; + } + + $tool = is_string($tool) ? app($tool) : $tool; + + $names[] = $tool instanceof Tool ? $tool->name() : get_debug_type($tool); + } + + return $names; + } + + /** + * The tool names of a `tools/list` answer, in the order the client got + * them. + * + * @return list + */ + public static function listed(TestListResponse $response): array + { + /** @var list */ + return (fn (): array => array_values(array_column($this->items, 'name')))->call($response); + } +} From 627306c88036d099d86ee1be9b14386cb2027b11 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:42:04 -0400 Subject: [PATCH 10/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 6 HTTP and MCP surfaces and resource payload Co-Authored-By: Claude Opus 5.5 (1M context) --- .../Controllers/McpServerToolsController.php | 23 ++ .../ClearConcreteServerToolsRequest.php | 32 ++ .../UpdateConcreteServerToolsRequest.php | 34 ++ .../Http/Resources/McpServerResource.php | 19 +- .../Requests/ClearServerToolsMcpRequest.php | 32 ++ .../Requests/UpdateServerToolsMcpRequest.php | 33 ++ .../Mcp/Tools/ClearServerToolsTool.php | 28 ++ .../Mcp/Tools/UpdateServerToolsTool.php | 36 ++ .../Resources/McpInstructionResource.php | 10 + .../Services/McpServerRegistry.php | 17 +- .../Services/ServerToolResolver.php | 54 ++- src/Domains/ConcreteServer/routes.php | 4 + src/Mcp/CortexServer.php | 6 +- .../Feature/Http/ConcreteServerToolsTest.php | 328 ++++++++++++++++++ tests/Feature/Mcp/OutputSchemaTest.php | 2 +- tests/Feature/Mcp/ServerToolsToolsTest.php | 185 ++++++++++ tests/Feature/ToolOnlyRowTest.php | 104 ++++++ 17 files changed, 935 insertions(+), 12 deletions(-) create mode 100644 src/Domains/ConcreteServer/Http/Controllers/McpServerToolsController.php create mode 100644 src/Domains/ConcreteServer/Http/Requests/ClearConcreteServerToolsRequest.php create mode 100644 src/Domains/ConcreteServer/Http/Requests/UpdateConcreteServerToolsRequest.php create mode 100644 src/Domains/ConcreteServer/Mcp/Requests/ClearServerToolsMcpRequest.php create mode 100644 src/Domains/ConcreteServer/Mcp/Requests/UpdateServerToolsMcpRequest.php create mode 100644 src/Domains/ConcreteServer/Mcp/Tools/ClearServerToolsTool.php create mode 100644 src/Domains/ConcreteServer/Mcp/Tools/UpdateServerToolsTool.php create mode 100644 tests/Feature/Http/ConcreteServerToolsTest.php create mode 100644 tests/Feature/Mcp/ServerToolsToolsTest.php create mode 100644 tests/Feature/ToolOnlyRowTest.php diff --git a/src/Domains/ConcreteServer/Http/Controllers/McpServerToolsController.php b/src/Domains/ConcreteServer/Http/Controllers/McpServerToolsController.php new file mode 100644 index 0000000..c525946 --- /dev/null +++ b/src/Domains/ConcreteServer/Http/Controllers/McpServerToolsController.php @@ -0,0 +1,23 @@ +persist(); + } + + public function destroy(ClearConcreteServerToolsRequest $request, string $server): Response + { + return $request->persist(); + } +} diff --git a/src/Domains/ConcreteServer/Http/Requests/ClearConcreteServerToolsRequest.php b/src/Domains/ConcreteServer/Http/Requests/ClearConcreteServerToolsRequest.php new file mode 100644 index 0000000..ced705f --- /dev/null +++ b/src/Domains/ConcreteServer/Http/Requests/ClearConcreteServerToolsRequest.php @@ -0,0 +1,32 @@ +allows('updateTools', $this->instructionOrNew()); + } + + public function rules(): array + { + return ClearConcreteServerToolsData::rules($this->serverName()); + } + + public function persist(): Response + { + app(ClearConcreteServerToolsAction::class)->execute( + $this->serverName(), + ClearConcreteServerToolsData::fromValidated($this->validated()), + ); + + return response()->noContent(); + } +} diff --git a/src/Domains/ConcreteServer/Http/Requests/UpdateConcreteServerToolsRequest.php b/src/Domains/ConcreteServer/Http/Requests/UpdateConcreteServerToolsRequest.php new file mode 100644 index 0000000..f1dbafc --- /dev/null +++ b/src/Domains/ConcreteServer/Http/Requests/UpdateConcreteServerToolsRequest.php @@ -0,0 +1,34 @@ +allows('updateTools', $this->instructionOrNew()); + } + + public function rules(): array + { + return UpdateConcreteServerToolsData::rules($this->serverName()); + } + + public function persist(): JsonResponse + { + $instruction = app(UpdateConcreteServerToolsAction::class)->execute( + $this->serverName(), + UpdateConcreteServerToolsData::fromValidated($this->validated()), + ); + + // PUT sets state, so it answers 200 even when it first creates the row. + return (new McpInstructionResource($instruction))->response()->setStatusCode(200); + } +} diff --git a/src/Domains/ConcreteServer/Http/Resources/McpServerResource.php b/src/Domains/ConcreteServer/Http/Resources/McpServerResource.php index 703f98c..86712c5 100644 --- a/src/Domains/ConcreteServer/Http/Resources/McpServerResource.php +++ b/src/Domains/ConcreteServer/Http/Resources/McpServerResource.php @@ -7,9 +7,19 @@ use Illuminate\Contracts\JsonSchema\JsonSchema; use Illuminate\Http\Request; use Illuminate\JsonSchema\Types\Type; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpToolOverrides; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\ServerToolResolver; use RefactorCircus\Keystone\Http\Resources\JsonResource; /** + * A registered MCP server with its effective instructions and tools. + * + * `tools` is what the server serves, by stored entry and in stored order + * while a tool override applies, else its code tools by name; + * `missing_tools` and `ambiguous_tools` name the stored entries that serve + * nothing and those that also name a registered Cortex tool (see + * {@see ServerToolResolver::report()}). + * * @property array{name: string, class: string, instructions: string} $resource */ final class McpServerResource extends JsonResource @@ -22,6 +32,10 @@ public static function schema(JsonSchema $schema): array return [ 'name' => $schema->string()->required(), 'instructions' => $schema->string()->required(), + 'tools' => $schema->array()->items($schema->string())->required(), + 'tools_overridden' => $schema->boolean()->required(), + 'missing_tools' => $schema->array()->items($schema->string())->required(), + 'ambiguous_tools' => $schema->array()->items($schema->string())->required(), ]; } @@ -30,9 +44,12 @@ public static function schema(JsonSchema $schema): array */ public function toArray(Request $request): array { + $name = $this->resource['name']; + return [ - 'name' => $this->resource['name'], + 'name' => $name, 'instructions' => $this->resource['instructions'], + ...app(ServerToolResolver::class)->report($name, app(McpToolOverrides::class)->for($name)), ]; } } diff --git a/src/Domains/ConcreteServer/Mcp/Requests/ClearServerToolsMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/ClearServerToolsMcpRequest.php new file mode 100644 index 0000000..f7d9eb0 --- /dev/null +++ b/src/Domains/ConcreteServer/Mcp/Requests/ClearServerToolsMcpRequest.php @@ -0,0 +1,32 @@ +allows('updateTools', $this->instructionOrNew()); + } + + protected function rules(): array + { + return $this->serverRules() + ClearConcreteServerToolsData::rules($this->serverName()); + } + + protected function handle(array $validated): Response + { + app(ClearConcreteServerToolsAction::class)->execute( + $this->serverName(), + ClearConcreteServerToolsData::fromValidated($validated), + ); + + return Response::text('Server tool override cleared. The server serves its code-declared tools.'); + } +} diff --git a/src/Domains/ConcreteServer/Mcp/Requests/UpdateServerToolsMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/UpdateServerToolsMcpRequest.php new file mode 100644 index 0000000..26508e1 --- /dev/null +++ b/src/Domains/ConcreteServer/Mcp/Requests/UpdateServerToolsMcpRequest.php @@ -0,0 +1,33 @@ +allows('updateTools', $this->instructionOrNew()); + } + + protected function rules(): array + { + return $this->serverRules() + UpdateConcreteServerToolsData::rules($this->serverName()); + } + + protected function handle(array $validated): ResponseFactory + { + $instruction = app(UpdateConcreteServerToolsAction::class)->execute( + $this->serverName(), + UpdateConcreteServerToolsData::fromValidated($validated), + ); + + return (new McpInstructionResource($instruction))->toStructuredResponse(); + } +} diff --git a/src/Domains/ConcreteServer/Mcp/Tools/ClearServerToolsTool.php b/src/Domains/ConcreteServer/Mcp/Tools/ClearServerToolsTool.php new file mode 100644 index 0000000..5c931c7 --- /dev/null +++ b/src/Domains/ConcreteServer/Mcp/Tools/ClearServerToolsTool.php @@ -0,0 +1,28 @@ +persist(); + } + + public function schema(JsonSchema $schema): array + { + return [ + 'server' => $schema->string()->description('The registered MCP server name.')->required(), + ]; + } +} diff --git a/src/Domains/ConcreteServer/Mcp/Tools/UpdateServerToolsTool.php b/src/Domains/ConcreteServer/Mcp/Tools/UpdateServerToolsTool.php new file mode 100644 index 0000000..4093e89 --- /dev/null +++ b/src/Domains/ConcreteServer/Mcp/Tools/UpdateServerToolsTool.php @@ -0,0 +1,36 @@ +persist(); + } + + public function schema(JsonSchema $schema): array + { + return [ + 'server' => $schema->string()->description('The registered MCP server name.')->required(), + 'tools' => $schema->array()->items($schema->string())->nullable() + ->description('Tool names to serve, in order, or null to serve the tools declared in code.')->required(), + ]; + } + + public function outputSchema(JsonSchema $schema): array + { + return McpInstructionResource::structuredSchema($schema); + } +} diff --git a/src/Domains/ConcreteServer/Resources/McpInstructionResource.php b/src/Domains/ConcreteServer/Resources/McpInstructionResource.php index 2ad29d0..c4f236e 100644 --- a/src/Domains/ConcreteServer/Resources/McpInstructionResource.php +++ b/src/Domains/ConcreteServer/Resources/McpInstructionResource.php @@ -8,9 +8,14 @@ use Illuminate\Http\Request; use Illuminate\JsonSchema\Types\Type; use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\ServerToolResolver; use RefactorCircus\Keystone\Http\Resources\JsonResource; /** + * A server's override row: its published instructions and its tools, with + * the same tool fields as {@see McpServerResource} (see + * {@see ServerToolResolver::report()}), taken from the row's own `tools`. + * * @mixin McpInstructionModel */ final class McpInstructionResource extends JsonResource @@ -24,6 +29,10 @@ public static function schema(JsonSchema $schema): array 'server' => $schema->string()->required(), 'published_version' => $schema->integer()->nullable()->required(), 'published_content' => $schema->string()->nullable()->required(), + 'tools' => $schema->array()->items($schema->string())->required(), + 'tools_overridden' => $schema->boolean()->required(), + 'missing_tools' => $schema->array()->items($schema->string())->required(), + 'ambiguous_tools' => $schema->array()->items($schema->string())->required(), 'created_at' => $schema->string()->nullable()->required(), 'updated_at' => $schema->string()->nullable()->required(), ]; @@ -38,6 +47,7 @@ public function toArray(Request $request): array 'server' => $this->server, 'published_version' => $this->publishedVersion?->version, 'published_content' => $this->publishedVersion?->content, + ...app(ServerToolResolver::class)->report($this->server, $this->tools), 'created_at' => $this->created_at?->toIso8601String(), 'updated_at' => $this->updated_at?->toIso8601String(), ]; diff --git a/src/Domains/ConcreteServer/Services/McpServerRegistry.php b/src/Domains/ConcreteServer/Services/McpServerRegistry.php index 9efa9a4..91f782a 100644 --- a/src/Domains/ConcreteServer/Services/McpServerRegistry.php +++ b/src/Domains/ConcreteServer/Services/McpServerRegistry.php @@ -128,11 +128,9 @@ public function defaultInstructions(string $name): string */ public function defaultTools(string $name): array { - $default = (new ReflectionClass($this->get($name)))->getProperty('tools')->getDefaultValue(); - $names = []; - foreach (is_array($default) ? $default : [] as $entry) { + foreach ($this->declaredTools($name) as $entry) { foreach (is_array($entry) ? $entry : [$entry] as $tool) { $names[] = $this->toolName($tool); } @@ -141,6 +139,19 @@ public function defaultTools(string $name): array return $names; } + /** + * The server class's `$tools` default as declared (classes, instances + * and ToolSearch groups), read without building the server. + * + * @return array + */ + public function declaredTools(string $name): array + { + $default = (new ReflectionClass($this->get($name)))->getProperty('tools')->getDefaultValue(); + + return is_array($default) ? $default : []; + } + /** * Whether Cortex may override the server's tool list. Every registered * server may except Cortex's own, by its registered name: the same class diff --git a/src/Domains/ConcreteServer/Services/ServerToolResolver.php b/src/Domains/ConcreteServer/Services/ServerToolResolver.php index 3152b53..d4a650e 100644 --- a/src/Domains/ConcreteServer/Services/ServerToolResolver.php +++ b/src/Domains/ConcreteServer/Services/ServerToolResolver.php @@ -34,8 +34,48 @@ public function __construct( private readonly ToolRegistry $registry, private readonly ToolDescriptionOverrides $descriptions, private readonly WarningLimiter $warnings, + private readonly McpServerRegistry $servers, ) {} + /** + * What a server's tool override amounts to, for its resources (AC 15), + * without logging: the tools it serves, by entry and in stored order (its + * code tools by name without an override), whether an override applies, + * the stored entries that resolve to no tool or whose tool throws while + * built, and the entries that name a code tool and a registered tool. + * + * The code tools are the server class's declared ones, as validation + * reads them; tools a server adds at runtime are not seen here. A stored + * value that is not a list, and any value on a server whose tools cannot + * be overridden (the `cortex` server), is no override. + * + * @return array{tools: list, tools_overridden: bool, missing_tools: list, ambiguous_tools: list} + */ + public function report(string $server, mixed $stored): array + { + if (! $this->servers->has($server)) { + return ['tools' => [], 'tools_overridden' => false, 'missing_tools' => [], 'ambiguous_tools' => []]; + } + + if (! is_array($stored) || ! $this->servers->supportsToolOverrides($server)) { + return [ + 'tools' => $this->servers->defaultTools($server), + 'tools_overridden' => false, + 'missing_tools' => [], + 'ambiguous_tools' => [], + ]; + } + + $resolved = $this->resolve($this->servers->declaredTools($server), array_values(array_filter($stored, is_string(...)))); + + return [ + 'tools' => $resolved['entries'], + 'tools_overridden' => true, + 'missing_tools' => $resolved['missing'], + 'ambiguous_tools' => $resolved['ambiguous'], + ]; + } + /** * The tools to serve, in stored order. Entries that resolve to no tool, * whose tool throws while built (D-016, D-022) or that also name a @@ -96,14 +136,14 @@ public function serve(string $server, array $codeTools, array $entries): array /** * What the stored entries resolve to, without logging: the tools to - * serve in stored order, the entries that resolve to nothing or whose - * tool threw (`missing`, in stored order), the message of each throw - * (`failed`) and the entries that name a code tool and a registered tool - * (`ambiguous`). + * serve in stored order and the entries they were served for + * (`entries`), the entries that resolve to nothing or whose tool threw + * (`missing`, in stored order), the message of each throw (`failed`) and + * the entries that name a code tool and a registered tool (`ambiguous`). * * @param array $codeTools the context's tools as declared * @param list $entries - * @return array{tools: list, missing: list, failed: array, ambiguous: list} + * @return array{tools: list, entries: list, missing: list, failed: array, ambiguous: list} */ public function resolve(array $codeTools, array $entries): array { @@ -111,6 +151,7 @@ public function resolve(array $codeTools, array $entries): array $registered = $this->registeredClasses(); $tools = []; + $servedEntries = []; $served = []; $missing = []; $failed = []; @@ -146,9 +187,10 @@ public function resolve(array $codeTools, array $entries): array $served[$tool->name()] = true; $tools[] = $tool; + $servedEntries[] = $entry; } - return ['tools' => $tools, 'missing' => $missing, 'failed' => $failed, 'ambiguous' => $ambiguous]; + return ['tools' => $tools, 'entries' => $servedEntries, 'missing' => $missing, 'failed' => $failed, 'ambiguous' => $ambiguous]; } /** diff --git a/src/Domains/ConcreteServer/routes.php b/src/Domains/ConcreteServer/routes.php index 826b356..29bb9f4 100644 --- a/src/Domains/ConcreteServer/routes.php +++ b/src/Domains/ConcreteServer/routes.php @@ -5,9 +5,13 @@ use Illuminate\Support\Facades\Route; use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Controllers\McpInstructionController; use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Controllers\McpServerController; +use RefactorCircus\Cortex\Domains\ConcreteServer\Http\Controllers\McpServerToolsController; Route::get('servers', [McpServerController::class, 'index'])->name('servers.index'); +Route::put('servers/{server}/tools', [McpServerToolsController::class, 'update'])->name('servers.tools.update'); +Route::delete('servers/{server}/tools', [McpServerToolsController::class, 'destroy'])->name('servers.tools.destroy'); + Route::get('servers/{server}/instructions', [McpInstructionController::class, 'show'])->name('servers.instructions.show'); Route::delete('servers/{server}/instructions', [McpInstructionController::class, 'destroy'])->name('servers.instructions.destroy'); Route::get('servers/{server}/instructions/versions', [McpInstructionController::class, 'versions'])->name('servers.instructions.versions.index'); diff --git a/src/Mcp/CortexServer.php b/src/Mcp/CortexServer.php index c8fb657..84c8cd9 100644 --- a/src/Mcp/CortexServer.php +++ b/src/Mcp/CortexServer.php @@ -17,12 +17,14 @@ use RefactorCircus\Cortex\Domains\ConcreteAgent\Mcp\Tools\RunConcreteAgentTool; use RefactorCircus\Cortex\Domains\ConcreteAgent\Mcp\Tools\ShowConcreteAgentTool; use RefactorCircus\Cortex\Domains\ConcreteAgent\Mcp\Tools\UpdateConcreteAgentToolsTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ClearServerToolsTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\CreateServerInstructionVersionTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\DeleteServerInstructionsTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ListServerInstructionVersionsTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ListServersTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\PublishServerInstructionVersionTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ShowServerInstructionsTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\UpdateServerToolsTool; use RefactorCircus\Cortex\Domains\RedirectDomain\Mcp\Tools\CreateRedirectDomainTool; use RefactorCircus\Cortex\Domains\RedirectDomain\Mcp\Tools\DeleteRedirectDomainTool; use RefactorCircus\Cortex\Domains\RedirectDomain\Mcp\Tools\ListRedirectDomainsTool; @@ -42,7 +44,7 @@ #[Name('Cortex')] #[Version('1.0.0')] -#[Instructions('Manage Cortex virtual agents, concrete agents, tools, and MCP server instructions. Virtual agents live in the database: each holds its own versioned prompt (content is immutable per version; the published version runs), registered tools, and optional virtual or concrete sub-agents, and runs with run-virtual-agent. Concrete agents are classes registered in code; their prompt and toolset can be overridden (prompt overrides are versioned and published), and they run with run-concrete-agent. Registered MCP servers hold versioned instruction overrides that replace their code-declared instructions when published. Redirect domains are the origins MCP clients may register OAuth redirect URIs on, beside the configured ones.')] +#[Instructions('Manage Cortex virtual agents, concrete agents, tools, and MCP server instructions. Virtual agents live in the database: each holds its own versioned prompt (content is immutable per version; the published version runs), registered tools, and optional virtual or concrete sub-agents, and runs with run-virtual-agent. Concrete agents are classes registered in code; their prompt and toolset can be overridden (prompt overrides are versioned and published), and they run with run-concrete-agent. Registered MCP servers hold versioned instruction overrides that replace their code-declared instructions when published, and a tool list override (update-server-tools-tool, cleared with clear-server-tools-tool) that replaces their code-declared tools. Redirect domains are the origins MCP clients may register OAuth redirect URIs on, beside the configured ones.')] final class CortexServer extends Server { /** @@ -85,6 +87,8 @@ final class CortexServer extends Server CreateServerInstructionVersionTool::class, PublishServerInstructionVersionTool::class, DeleteServerInstructionsTool::class, + UpdateServerToolsTool::class, + ClearServerToolsTool::class, // OAuth redirect domains ListRedirectDomainsTool::class, diff --git a/tests/Feature/Http/ConcreteServerToolsTest.php b/tests/Feature/Http/ConcreteServerToolsTest.php new file mode 100644 index 0000000..9d05500 --- /dev/null +++ b/tests/Feature/Http/ConcreteServerToolsTest.php @@ -0,0 +1,328 @@ +flush(); + + app(McpServerRegistry::class)->register('grouped', GroupedToolsServer::class); + app(ToolRegistry::class)->register('echo-cortex-tool', EchoCortexTool::class); +}); + +/** + * Write the grouped server's override row directly, for values the update + * action refuses (stale entries, a corrupt value), then start a new request. + */ +function writeHttpServerTools(string $server, mixed $tools): void +{ + McpInstructionModel::query()->updateOrCreate(['server' => $server], ['tools' => null]); + + DB::table(Tables::name('mcp_instructions'))->where('server', $server)->update([ + 'tools' => $tools === null ? null : json_encode($tools, JSON_THROW_ON_ERROR), + ]); + + $cache = app(PublicationCache::class); + $cache->forget($cache->mcpToolsKey(), $cache->mcpInstructionsKey()); + + app()->forgetScopedInstances(); +} + +/** + * The server's entry in the server list, read in a new request. + * + * @return array + */ +function listedHttpServer(string $server): array +{ + app()->forgetScopedInstances(); + + /** @var array */ + return collect(test()->getJson(route('cortex.servers.index'))->assertOk()->json('data'))->firstWhere('name', $server); +} + +/** + * The server's instructions show payload, read in a new request. + * + * @return array + */ +function shownHttpServer(string $server): array +{ + app()->forgetScopedInstances(); + + /** @var array */ + return test()->getJson(route('cortex.servers.instructions.show', $server))->assertOk()->json('data'); +} + +/** + * @return list|null + */ +function storedHttpServerTools(string $server): ?array +{ + $value = McpInstructionModel::query()->where('server', $server)->value('tools'); + + return is_string($value) ? json_decode($value, true) : $value; +} + +describe('PUT cortex.servers.tools.update', function (): void { + it('stores the list and answers with the server resource', function (): void { + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-cortex-tool', 'echo-mcp-tool']]) + ->assertOk() + ->assertJsonPath('data.server', 'grouped') + ->assertJsonPath('data.tools', ['echo-cortex-tool', 'echo-mcp-tool']) + ->assertJsonPath('data.tools_overridden', true) + ->assertJsonPath('data.missing_tools', []) + ->assertJsonPath('data.ambiguous_tools', []); + + expect(McpInstructionModel::query()->where('server', 'grouped')->sole()->tools)->toBe(['echo-cortex-tool', 'echo-mcp-tool']); + }); + + it('answers 200 for a null list, which keeps the code tools', function (): void { + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => null]) + ->assertOk() + ->assertJsonPath('data.tools', ['echo-mcp-tool', 'echo-request-tool', 'renamed-echo']) + ->assertJsonPath('data.tools_overridden', false); + }); + + it('maps a refused entry and a missing key to 422 on the field', function (): void { + $route = route('cortex.servers.tools.update', 'grouped'); + + $this->putJson($route, ['tools' => ['echo-mcp-tool', 'gone-tool']]) + ->assertUnprocessable() + ->assertJsonValidationErrors(['tools.1']) + ->assertJsonMissingValidationErrors(['tools.0']); + + $this->putJson($route, [])->assertUnprocessable()->assertJsonValidationErrors(['tools']); + + expect(McpInstructionModel::query()->count())->toBe(0); + }); + + it('refuses the cortex server with a 422', function (): void { + $this->putJson(route('cortex.servers.tools.update', 'cortex'), ['tools' => []]) + ->assertUnprocessable() + ->assertJsonValidationErrors(['server']); + + expect(McpInstructionModel::query()->count())->toBe(0); + }); + + it('answers 404 for an unknown server', function (): void { + $this->putJson(route('cortex.servers.tools.update', 'missing'), ['tools' => []])->assertNotFound(); + }); +}); + +describe('DELETE cortex.servers.tools.destroy', function (): void { + it('clears a tool-only override, removing the row', function (): void { + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-mcp-tool']])->assertOk(); + + $this->deleteJson(route('cortex.servers.tools.destroy', 'grouped'))->assertNoContent(); + + expect(McpInstructionModel::query()->count())->toBe(0) + ->and(listedHttpServer('grouped'))->toMatchArray([ + 'tools' => ['echo-mcp-tool', 'echo-request-tool', 'renamed-echo'], + 'tools_overridden' => false, + ]); + }); + + it('clears the tools and keeps the published instructions', function (): void { + $this->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Kept.', 'publish' => true])->assertCreated(); + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-mcp-tool']])->assertOk(); + + $this->deleteJson(route('cortex.servers.tools.destroy', 'grouped'))->assertNoContent(); + + expect(McpInstructionModel::query()->where('server', 'grouped')->sole()->tools)->toBeNull() + ->and(shownHttpServer('grouped'))->toMatchArray([ + 'published_version' => 1, + 'published_content' => 'Kept.', + 'tools_overridden' => false, + ]); + }); + + it('answers 204 for a server without a tool override', function (): void { + $this->deleteJson(route('cortex.servers.tools.destroy', 'grouped'))->assertNoContent(); + + expect(McpInstructionModel::query()->count())->toBe(0); + }); + + it('refuses the cortex server with a 422 and answers 404 for an unknown server', function (): void { + $this->deleteJson(route('cortex.servers.tools.destroy', 'cortex')) + ->assertUnprocessable() + ->assertJsonValidationErrors(['server']); + + $this->deleteJson(route('cortex.servers.tools.destroy', 'missing'))->assertNotFound(); + }); +}); + +describe('authorization', function (): void { + it('refuses a guest with 401 and a signed-in user with 403 under a policy without updateTools, keeping the stored list', function (): void { + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-mcp-tool']])->assertOk(); + + Gate::policy(McpInstructionModel::class, NoUpdateToolsMcpInstructionPolicy::class); + + $update = route('cortex.servers.tools.update', 'grouped'); + $clear = route('cortex.servers.tools.destroy', 'grouped'); + + $this->putJson($update, ['tools' => ['echo-cortex-tool']])->assertUnauthorized(); + $this->deleteJson($clear)->assertUnauthorized(); + + $this->actingAs(new GenericUser(['id' => 1])); + + $this->putJson($update, ['tools' => ['echo-cortex-tool']])->assertForbidden(); + $this->deleteJson($clear)->assertForbidden(); + + expect(McpInstructionModel::query()->where('server', 'grouped')->sole()->tools)->toBe(['echo-mcp-tool']); + }); + + it('checks the server without an override row against the policy too', function (): void { + Gate::policy(McpInstructionModel::class, NoUpdateToolsMcpInstructionPolicy::class); + + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-cortex-tool']])->assertUnauthorized(); + + expect(McpInstructionModel::query()->count())->toBe(0); + }); +}); + +describe('resource payload (AC 15)', function (): void { + it('reports the code tools and no override for a server without a row', function (): void { + expect(listedHttpServer('grouped'))->toMatchArray([ + 'tools' => ['echo-mcp-tool', 'echo-request-tool', 'renamed-echo'], + 'tools_overridden' => false, + 'missing_tools' => [], + 'ambiguous_tools' => [], + ]); + }); + + it('reports a valid override on the list and the show payload, in stored order', function (): void { + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['renamed-echo', 'echo-cortex-tool', 'echo-mcp-tool']])->assertOk(); + + $expected = [ + 'tools' => ['renamed-echo', 'echo-cortex-tool', 'echo-mcp-tool'], + 'tools_overridden' => true, + 'missing_tools' => [], + 'ambiguous_tools' => [], + ]; + + expect(listedHttpServer('grouped'))->toMatchArray($expected) + ->and(shownHttpServer('grouped'))->toMatchArray($expected); + }); + + it('reports an empty list as an override serving no tools', function (): void { + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => []]) + ->assertOk() + ->assertJsonPath('data.tools', []) + ->assertJsonPath('data.tools_overridden', true); + }); + + it('reports a stale entry in missing_tools and leaves it out of tools', function (): void { + writeHttpServerTools('grouped', ['gone-tool', 'echo-mcp-tool']); + + $expected = [ + 'tools' => ['echo-mcp-tool'], + 'tools_overridden' => true, + 'missing_tools' => ['gone-tool'], + 'ambiguous_tools' => [], + ]; + + expect(listedHttpServer('grouped'))->toMatchArray($expected) + ->and(shownHttpServer('grouped'))->toMatchArray($expected); + }); + + it('reports an entry whose tool throws while built in missing_tools', function (): void { + app(ToolRegistry::class)->register('throwing-cortex-tool', ThrowingCortexTool::class); + + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['throwing-cortex-tool', 'echo-mcp-tool']]) + ->assertOk() + ->assertJsonPath('data.tools', ['echo-mcp-tool']) + ->assertJsonPath('data.missing_tools', ['throwing-cortex-tool']); + + expect(listedHttpServer('grouped'))->toMatchArray([ + 'tools' => ['echo-mcp-tool'], + 'missing_tools' => ['throwing-cortex-tool'], + ]); + }); + + it('reports an entry naming a code tool and a registered tool in ambiguous_tools, without logging', function (): void { + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-mcp-tool', 'renamed-echo']])->assertOk(); + + // Registered after the save, under a code tool's name. + app(ToolRegistry::class)->register('echo-mcp-tool', CollidingCortexTool::class); + + Log::spy(); + + $expected = [ + 'tools' => ['echo-mcp-tool', 'renamed-echo'], + 'tools_overridden' => true, + 'missing_tools' => [], + 'ambiguous_tools' => ['echo-mcp-tool'], + ]; + + expect(listedHttpServer('grouped'))->toMatchArray($expected) + ->and(shownHttpServer('grouped'))->toMatchArray($expected); + + Log::shouldNotHaveReceived('warning'); + }); + + it('reports a corrupt stored value as no override', function (): void { + writeHttpServerTools('grouped', 'echo-mcp-tool'); + + expect(shownHttpServer('grouped'))->toMatchArray([ + 'tools' => ['echo-mcp-tool', 'echo-request-tool', 'renamed-echo'], + 'tools_overridden' => false, + ]); + }); + + it('reports the cortex server as not overridden, with or without a stored tools row', function (): void { + $codeTools = app(McpServerRegistry::class)->defaultTools('cortex'); + + expect(listedHttpServer('cortex'))->toMatchArray(['tools' => $codeTools, 'tools_overridden' => false]); + + writeHttpServerTools('cortex', ['list-tools-tool']); + + expect(listedHttpServer('cortex'))->toMatchArray([ + 'tools' => $codeTools, + 'tools_overridden' => false, + 'missing_tools' => [], + 'ambiguous_tools' => [], + ]) + ->and(shownHttpServer('cortex'))->toMatchArray(['tools' => $codeTools, 'tools_overridden' => false]); + }); +}); + +it('keeps the tool override when the instructions are deleted, and the payload says so (AC 11)', function (): void { + $this->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Published.', 'publish' => true])->assertCreated(); + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-mcp-tool']])->assertOk(); + + $this->deleteJson(route('cortex.servers.instructions.destroy', 'grouped'))->assertSuccessful(); + + expect(storedHttpServerTools('grouped'))->toBe(['echo-mcp-tool']) + ->and(shownHttpServer('grouped'))->toMatchArray([ + 'published_version' => null, + 'tools' => ['echo-mcp-tool'], + 'tools_overridden' => true, + ]) + ->and(listedHttpServer('grouped'))->toMatchArray([ + 'instructions' => 'Grouped tools server instructions.', + 'tools_overridden' => true, + ]); +}); diff --git a/tests/Feature/Mcp/OutputSchemaTest.php b/tests/Feature/Mcp/OutputSchemaTest.php index 40c51b2..85da142 100644 --- a/tests/Feature/Mcp/OutputSchemaTest.php +++ b/tests/Feature/Mcp/OutputSchemaTest.php @@ -25,6 +25,6 @@ ->values() ->all(); - expect($structured->count())->toBe(25) + expect($structured->count())->toBe(26) ->and($missing)->toBe([]); }); diff --git a/tests/Feature/Mcp/ServerToolsToolsTest.php b/tests/Feature/Mcp/ServerToolsToolsTest.php new file mode 100644 index 0000000..359ebc1 --- /dev/null +++ b/tests/Feature/Mcp/ServerToolsToolsTest.php @@ -0,0 +1,185 @@ +flush(); + + app(McpServerRegistry::class)->register('grouped', GroupedToolsServer::class); + app(ToolRegistry::class)->register('echo-cortex-tool', EchoCortexTool::class); +}); + +/** + * The grouped server's stored row as the parity tests compare it: keys are + * generated per row, so versions are compared by number. + * + * @return array{tools: mixed, published_version: int|null, versions: list}|null + */ +function mcpParityServerRow(): ?array +{ + $instruction = McpInstructionModel::query()->where('server', 'grouped')->first(); + + return $instruction === null ? null : [ + 'tools' => $instruction->tools, + 'published_version' => $instruction->publishedVersion?->version, + 'versions' => $instruction->versions()->pluck('version')->map(fn (mixed $version): int => (int) $version)->values()->all(), + ]; +} + +it('lists the tools as update-server-tools-tool and clear-server-tools-tool on the cortex server', function (): void { + expect(CortexServer::TOOLS)->toContain(UpdateServerToolsTool::class, ClearServerToolsTool::class) + ->and(app(UpdateServerToolsTool::class)->name())->toBe('update-server-tools-tool') + ->and(app(ClearServerToolsTool::class)->name())->toBe('clear-server-tools-tool'); +}); + +describe('update-server-tools-tool', function (): void { + it('stores the same state and answers the same payload as the HTTP route', function (?array $tools): void { + app(ToolRegistry::class)->register('throwing-cortex-tool', ThrowingCortexTool::class); + $this->freezeTime(); + + $http = $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => $tools])->assertOk()->json('data'); + $httpRow = mcpParityServerRow(); + + McpInstructionModel::query()->delete(); + app()->forgetScopedInstances(); + + mcpTool(UpdateServerToolsTool::class, ['server' => 'grouped', 'tools' => $tools]) + ->assertOk() + ->assertStructuredContent(['data' => $http]); + + expect(mcpParityServerRow())->toBe($httpRow); + })->with([ + 'valid entries' => [['echo-cortex-tool', 'renamed-echo']], + 'an entry whose tool throws' => [['throwing-cortex-tool', 'echo-mcp-tool']], + 'an empty list' => [[]], + 'null' => [null], + ]); + + it('answers the show payload, ambiguous entries included', function (): void { + mcpTool(UpdateServerToolsTool::class, ['server' => 'grouped', 'tools' => ['echo-mcp-tool']])->assertOk(); + + app(ToolRegistry::class)->register('echo-mcp-tool', CollidingCortexTool::class); + app()->forgetScopedInstances(); + + $http = $this->getJson(route('cortex.servers.instructions.show', 'grouped'))->json('data'); + + expect($http['ambiguous_tools'])->toBe(['echo-mcp-tool']); + + mcpTool(ShowServerInstructionsTool::class, ['server' => 'grouped']) + ->assertOk() + ->assertStructuredContent(['data' => $http]); + }); + + it('lists the tool fields with parity to the HTTP list', function (): void { + mcpTool(UpdateServerToolsTool::class, ['server' => 'grouped', 'tools' => ['renamed-echo']])->assertOk(); + app()->forgetScopedInstances(); + + $http = $this->getJson(route('cortex.servers.index'))->json('data'); + + expect(collect($http)->firstWhere('name', 'grouped'))->toMatchArray(['tools' => ['renamed-echo'], 'tools_overridden' => true]); + + mcpTool(ListServersTool::class) + ->assertOk() + ->assertStructuredContent(['data' => $http]); + }); + + it('errors on a refused entry and on the cortex server', function (): void { + mcpTool(UpdateServerToolsTool::class, ['server' => 'grouped', 'tools' => ['gone-tool']])->assertHasErrors(); + + mcpTool(UpdateServerToolsTool::class, ['server' => 'cortex', 'tools' => []]) + ->assertHasErrors(['The tools of the [cortex] server cannot be overridden.']); + + expect(McpInstructionModel::query()->count())->toBe(0); + }); + + it('errors not found for an unknown server', function (): void { + mcpTool(UpdateServerToolsTool::class, ['server' => 'missing', 'tools' => []])->assertHasErrors(['Not found.']); + }); +}); + +describe('clear-server-tools-tool', function (): void { + it('stores the same state as the HTTP route', function (bool $withInstructions): void { + $prepare = function () use ($withInstructions): void { + McpInstructionModel::query()->delete(); + + if ($withInstructions) { + $this->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Kept.', 'publish' => true])->assertCreated(); + } + + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-mcp-tool']])->assertOk(); + app()->forgetScopedInstances(); + }; + + $prepare(); + $this->deleteJson(route('cortex.servers.tools.destroy', 'grouped'))->assertNoContent(); + $httpRow = mcpParityServerRow(); + + $prepare(); + mcpTool(ClearServerToolsTool::class, ['server' => 'grouped']) + ->assertOk() + ->assertSee('Server tool override cleared.'); + + expect(mcpParityServerRow())->toBe($httpRow) + ->and($httpRow === null)->toBe(! $withInstructions); + })->with([ + 'a tool-only row' => [false], + 'a row with instructions' => [true], + ]); + + it('succeeds without a tool override', function (): void { + mcpTool(ClearServerToolsTool::class, ['server' => 'grouped'])->assertOk(); + + expect(McpInstructionModel::query()->count())->toBe(0); + }); + + it('errors on the cortex server and not found for an unknown server', function (): void { + mcpTool(ClearServerToolsTool::class, ['server' => 'cortex']) + ->assertHasErrors(['The tools of the [cortex] server cannot be overridden.']); + + mcpTool(ClearServerToolsTool::class, ['server' => 'missing'])->assertHasErrors(['Not found.']); + }); +}); + +it('refuses both tools under a policy without updateTools, keeping the stored list', function (): void { + mcpTool(UpdateServerToolsTool::class, ['server' => 'grouped', 'tools' => ['echo-mcp-tool']])->assertOk(); + + Gate::policy(McpInstructionModel::class, NoUpdateToolsMcpInstructionPolicy::class); + + mcpTool(UpdateServerToolsTool::class, ['server' => 'grouped', 'tools' => ['echo-cortex-tool']])->assertHasErrors(['Unauthorized.']); + mcpTool(ClearServerToolsTool::class, ['server' => 'grouped'])->assertHasErrors(['Unauthorized.']); + + expect(McpInstructionModel::query()->where('server', 'grouped')->sole()->tools)->toBe(['echo-mcp-tool']); +}); + +it('offers every concrete server action on HTTP and MCP', function (): void { + $domain = __DIR__.'/../../../src/Domains/ConcreteServer'; + + expect(Parity::gaps("{$domain}/Actions/*.php", [ + 'http' => "{$domain}/Http/Requests/*.php", + 'mcp' => "{$domain}/Mcp/Requests/*.php", + ]))->toBe([]); +}); diff --git a/tests/Feature/ToolOnlyRowTest.php b/tests/Feature/ToolOnlyRowTest.php new file mode 100644 index 0000000..247de1f --- /dev/null +++ b/tests/Feature/ToolOnlyRowTest.php @@ -0,0 +1,104 @@ +flush(); + + app(McpServerRegistry::class)->register('grouped', GroupedToolsServer::class); +}); + +// The tests take a Closure, so Pest hands each one over without calling it. +dataset('tool-only rows', [ + 'saved through the update action' => [function (): void { + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); + }], + 'left by deleting the instructions' => [function (): void { + test()->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Gone soon.', 'publish' => true])->assertCreated(); + app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); + test()->deleteJson(route('cortex.servers.instructions.destroy', 'grouped'))->assertSuccessful(); + }], +]); + +/** + * Create the tool-only row, check it is one, then start a new request. + */ +function makeToolOnlyRow(Closure $create): void +{ + $create(); + + $instruction = McpInstructionModel::query()->where('server', 'grouped')->sole(); + + expect($instruction->tools)->toBe(['echo-mcp-tool']) + ->and($instruction->published_version_id)->toBeNull() + ->and($instruction->versions()->count())->toBe(0); + + app()->forgetScopedInstances(); +} + +it('lists the server with its code instructions and the tool override', function (Closure $create): void { + makeToolOnlyRow($create); + + $listed = collect($this->getJson(route('cortex.servers.index'))->assertOk()->json('data'))->firstWhere('name', 'grouped'); + + expect($listed)->toMatchArray([ + 'instructions' => 'Grouped tools server instructions.', + 'tools' => ['echo-mcp-tool'], + 'tools_overridden' => true, + ]); +})->with('tool-only rows'); + +it('shows no published instructions and the tool override', function (Closure $create): void { + makeToolOnlyRow($create); + + $this->getJson(route('cortex.servers.instructions.show', 'grouped')) + ->assertOk() + ->assertJsonPath('data.published_version', null) + ->assertJsonPath('data.published_content', null) + ->assertJsonPath('data.tools', ['echo-mcp-tool']) + ->assertJsonPath('data.tools_overridden', true); +})->with('tool-only rows'); + +it('lists no versions', function (Closure $create): void { + makeToolOnlyRow($create); + + $this->getJson(route('cortex.servers.instructions.versions.index', 'grouped')) + ->assertOk() + ->assertJsonPath('data', []); + + mcpTool(ListServerInstructionVersionsTool::class, ['server' => 'grouped']) + ->assertOk() + ->assertStructuredContent(['data' => []]); +})->with('tool-only rows'); + +it('publishes a version on the row and keeps its tools', function (Closure $create): void { + makeToolOnlyRow($create); + + $this->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Draft.'])->assertCreated(); + + $this->postJson(route('cortex.servers.instructions.versions.publish', ['server' => 'grouped', 'version' => 1])) + ->assertOk() + ->assertJsonPath('data.published_version', 1) + ->assertJsonPath('data.published_content', 'Draft.') + ->assertJsonPath('data.tools', ['echo-mcp-tool']) + ->assertJsonPath('data.tools_overridden', true); + + expect(McpInstructionModel::query()->count())->toBe(1) + ->and(McpInstructionModel::query()->sole()->tools)->toBe(['echo-mcp-tool']); +})->with('tool-only rows'); From e830c2f490e182b04d8f173397e7d50cddf55e76 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sun, 25 Oct 2026 00:20:51 -0400 Subject: [PATCH 11/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 6 HTTP and MCP surfaces and resource payload D-057: DELETE cortex/servers/{server}/instructions and delete-server-instructions-tool answer 204/text when the override row is removed, and 200 McpInstructionResource / structured content when the row survives with its tool override. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../Actions/DeleteMcpInstructionAction.php | 16 ++++-- .../Controllers/McpInstructionController.php | 2 +- .../Requests/DeleteMcpInstructionRequest.php | 16 ++++-- .../DeleteServerInstructionsMcpRequest.php | 17 +++++-- .../Tools/DeleteServerInstructionsTool.php | 11 +++- .../DeleteMcpInstructionActionTest.php | 22 ++++++-- .../Feature/Http/ConcreteServerToolsTest.php | 29 ++++++++++- tests/Feature/Mcp/OutputSchemaTest.php | 2 +- tests/Feature/Mcp/ServerToolsToolsTest.php | 50 +++++++++++++++++++ tests/Feature/ToolOnlyRowTest.php | 4 +- 10 files changed, 151 insertions(+), 18 deletions(-) diff --git a/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php b/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php index 66b6460..f9a8f3b 100644 --- a/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php +++ b/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php @@ -18,23 +18,28 @@ * time (each fires its model events), and the published pointer. The * override row itself goes only when it holds no tool override, so a saved * tool list keeps applying. + * + * Returns the row when it survives (it still holds a tool override), or null + * when it was removed, so callers can answer with what is left. */ final class DeleteMcpInstructionAction { public function __construct(private readonly PublicationCache $cache) {} - public function execute(McpInstructionModel $instruction): void + public function execute(McpInstructionModel $instruction): ?McpInstructionModel { McpInstructionDeletingActionEvent::dispatch($instruction); - $this->perform($instruction); + $surviving = $this->perform($instruction); McpInstructionDeletedActionEvent::dispatch($instruction); + + return $surviving; } - private function perform(McpInstructionModel $instruction): void + private function perform(McpInstructionModel $instruction): ?McpInstructionModel { - DB::transaction(function () use ($instruction): void { + return DB::transaction(function () use ($instruction): ?McpInstructionModel { // Decided from the locked row, never from the copy passed in, so a // tool list saved after the action started is not lost. /** @var McpInstructionModel|null $locked */ @@ -48,6 +53,7 @@ private function perform(McpInstructionModel $instruction): void if ($locked->tools === null) { $locked->delete(); + $locked = null; } elseif ($locked->published_version_id !== null) { $locked->published_version_id = null; $locked->save(); @@ -55,6 +61,8 @@ private function perform(McpInstructionModel $instruction): void } DB::afterCommit(fn () => $this->forget($this->cache->mcpInstructionsKey(), $this->cache->mcpToolsKey())); + + return $locked; }); } diff --git a/src/Domains/ConcreteServer/Http/Controllers/McpInstructionController.php b/src/Domains/ConcreteServer/Http/Controllers/McpInstructionController.php index d21d837..b18f2a8 100644 --- a/src/Domains/ConcreteServer/Http/Controllers/McpInstructionController.php +++ b/src/Domains/ConcreteServer/Http/Controllers/McpInstructionController.php @@ -19,7 +19,7 @@ public function show(ShowMcpInstructionRequest $request, string $server): JsonRe return $request->persist(); } - public function destroy(DeleteMcpInstructionRequest $request, string $server): Response + public function destroy(DeleteMcpInstructionRequest $request, string $server): Response|JsonResponse { return $request->persist(); } diff --git a/src/Domains/ConcreteServer/Http/Requests/DeleteMcpInstructionRequest.php b/src/Domains/ConcreteServer/Http/Requests/DeleteMcpInstructionRequest.php index 519b0ba..0b03f52 100644 --- a/src/Domains/ConcreteServer/Http/Requests/DeleteMcpInstructionRequest.php +++ b/src/Domains/ConcreteServer/Http/Requests/DeleteMcpInstructionRequest.php @@ -4,8 +4,10 @@ namespace RefactorCircus\Cortex\Domains\ConcreteServer\Http\Requests; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Response; use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\DeleteMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionResource; final class DeleteMcpInstructionRequest extends McpInstructionRequest { @@ -14,10 +16,18 @@ public function authorize(): bool return $this->allows('delete', $this->instruction()); } - public function persist(): Response + /** + * 204 when the override row goes with its instructions; 200 with the row + * when it survives because it still holds a tool override (D-057). + */ + public function persist(): Response|JsonResponse { - app(DeleteMcpInstructionAction::class)->execute($this->instruction()); + $surviving = app(DeleteMcpInstructionAction::class)->execute($this->instruction()); - return response()->noContent(); + if ($surviving === null) { + return response()->noContent(); + } + + return (new McpInstructionResource($surviving))->response()->setStatusCode(200); } } diff --git a/src/Domains/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php index 95213b3..84a0be0 100644 --- a/src/Domains/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php +++ b/src/Domains/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php @@ -5,7 +5,9 @@ namespace RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests; use Laravel\Mcp\Response; +use Laravel\Mcp\ResponseFactory; use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\DeleteMcpInstructionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionResource; final class DeleteServerInstructionsMcpRequest extends ServerMcpRequest { @@ -19,10 +21,19 @@ protected function rules(): array return $this->serverRules(); } - protected function handle(array $validated): Response + /** + * Text when the override row goes with its instructions; the row as + * structured content when it survives because it still holds a tool + * override (D-057). + */ + protected function handle(array $validated): Response|ResponseFactory { - app(DeleteMcpInstructionAction::class)->execute($this->instruction()); + $surviving = app(DeleteMcpInstructionAction::class)->execute($this->instruction()); - return Response::text('Server instructions override deleted.'); + if ($surviving === null) { + return Response::text('Server instructions override deleted.'); + } + + return (new McpInstructionResource($surviving))->toStructuredResponse(); } } diff --git a/src/Domains/ConcreteServer/Mcp/Tools/DeleteServerInstructionsTool.php b/src/Domains/ConcreteServer/Mcp/Tools/DeleteServerInstructionsTool.php index 779593b..fde09c3 100644 --- a/src/Domains/ConcreteServer/Mcp/Tools/DeleteServerInstructionsTool.php +++ b/src/Domains/ConcreteServer/Mcp/Tools/DeleteServerInstructionsTool.php @@ -9,9 +9,10 @@ use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Attributes\Description; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Requests\DeleteServerInstructionsMcpRequest; +use RefactorCircus\Cortex\Domains\ConcreteServer\Resources\McpInstructionResource; use RefactorCircus\Keystone\Mcp\Tool; -#[Description('Remove the instruction override and its version history for a registered MCP server; the code-declared instructions take over.')] +#[Description('Remove the instruction override and its version history for a registered MCP server; the code-declared instructions take over. A tool override is kept: when the server still has one, the answer is its override row as structured content, otherwise a confirmation text.')] final class DeleteServerInstructionsTool extends Tool { public function handle(DeleteServerInstructionsMcpRequest $request): Response|ResponseFactory @@ -25,4 +26,12 @@ public function schema(JsonSchema $schema): array 'server' => $schema->string()->description('The registered MCP server name.')->required(), ]; } + + /** + * Covers the structured answer, given when the row survives with its tool override. + */ + public function outputSchema(JsonSchema $schema): array + { + return McpInstructionResource::structuredSchema($schema); + } } diff --git a/tests/Feature/DeleteMcpInstructionActionTest.php b/tests/Feature/DeleteMcpInstructionActionTest.php index 50b8751..16d0f4d 100644 --- a/tests/Feature/DeleteMcpInstructionActionTest.php +++ b/tests/Feature/DeleteMcpInstructionActionTest.php @@ -42,12 +42,27 @@ function deletableInstruction(?array $tools): McpInstructionModel return McpInstructionModel::query()->where('server', 'grouped')->firstOrFail(); } -function deleteInstructions(McpInstructionModel $instruction): void +function deleteInstructions(McpInstructionModel $instruction): ?McpInstructionModel { - app(DeleteMcpInstructionAction::class)->execute($instruction); + $surviving = app(DeleteMcpInstructionAction::class)->execute($instruction); app()->forgetScopedInstances(); + + return $surviving; } +it('reports the surviving row, or null when the row went (D-057)', function (): void { + $kept = deleteInstructions(deletableInstruction(['echo-mcp-tool'])); + + expect($kept)->toBeInstanceOf(McpInstructionModel::class) + ->and($kept?->server)->toBe('grouped') + ->and($kept?->tools)->toBe(['echo-mcp-tool']) + ->and($kept?->published_version_id)->toBeNull(); + + McpInstructionModel::query()->delete(); + + expect(deleteInstructions(deletableInstruction(null)))->toBeNull(); +}); + it('keeps a row holding a tool override, without its instructions', function (): void { $instruction = deletableInstruction(['renamed-echo', 'echo-mcp-tool']); @@ -151,11 +166,12 @@ function deleteInstructions(McpInstructionModel $instruction): void expect($instruction->tools)->toBeNull(); - deleteInstructions($instruction); + $surviving = deleteInstructions($instruction); $row = McpInstructionModel::query()->where('server', 'grouped')->first(); expect($written)->toBeTrue() + ->and($surviving?->tools)->toBe(['echo-request-tool']) ->and($row)->not->toBeNull() ->and($row?->tools)->toBe(['echo-request-tool']) ->and($row?->published_version_id)->toBeNull() diff --git a/tests/Feature/Http/ConcreteServerToolsTest.php b/tests/Feature/Http/ConcreteServerToolsTest.php index 9d05500..528ebdc 100644 --- a/tests/Feature/Http/ConcreteServerToolsTest.php +++ b/tests/Feature/Http/ConcreteServerToolsTest.php @@ -309,11 +309,38 @@ function storedHttpServerTools(string $server): ?array }); }); +describe('DELETE cortex.servers.instructions.destroy (D-057)', function (): void { + it('answers 204 when the row goes with its instructions', function (): void { + $this->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Published.', 'publish' => true])->assertCreated(); + + $this->deleteJson(route('cortex.servers.instructions.destroy', 'grouped'))->assertNoContent(); + + expect(McpInstructionModel::query()->count())->toBe(0); + }); + + it('answers 200 with the surviving row when it keeps a tool override (AC 11)', function (): void { + $this->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Published.', 'publish' => true])->assertCreated(); + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-mcp-tool']])->assertOk(); + + $this->deleteJson(route('cortex.servers.instructions.destroy', 'grouped')) + ->assertOk() + ->assertJsonPath('data.server', 'grouped') + ->assertJsonPath('data.published_version', null) + ->assertJsonPath('data.published_content', null) + ->assertJsonPath('data.tools', ['echo-mcp-tool']) + ->assertJsonPath('data.tools_overridden', true) + ->assertJsonPath('data.missing_tools', []) + ->assertJsonPath('data.ambiguous_tools', []); + }); +}); + it('keeps the tool override when the instructions are deleted, and the payload says so (AC 11)', function (): void { $this->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Published.', 'publish' => true])->assertCreated(); $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-mcp-tool']])->assertOk(); - $this->deleteJson(route('cortex.servers.instructions.destroy', 'grouped'))->assertSuccessful(); + $this->deleteJson(route('cortex.servers.instructions.destroy', 'grouped')) + ->assertOk() + ->assertJsonPath('data.tools_overridden', true); expect(storedHttpServerTools('grouped'))->toBe(['echo-mcp-tool']) ->and(shownHttpServer('grouped'))->toMatchArray([ diff --git a/tests/Feature/Mcp/OutputSchemaTest.php b/tests/Feature/Mcp/OutputSchemaTest.php index 85da142..b53e6f7 100644 --- a/tests/Feature/Mcp/OutputSchemaTest.php +++ b/tests/Feature/Mcp/OutputSchemaTest.php @@ -25,6 +25,6 @@ ->values() ->all(); - expect($structured->count())->toBe(26) + expect($structured->count())->toBe(27) ->and($missing)->toBe([]); }); diff --git a/tests/Feature/Mcp/ServerToolsToolsTest.php b/tests/Feature/Mcp/ServerToolsToolsTest.php index 359ebc1..56f7603 100644 --- a/tests/Feature/Mcp/ServerToolsToolsTest.php +++ b/tests/Feature/Mcp/ServerToolsToolsTest.php @@ -5,6 +5,7 @@ use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Gate; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ClearServerToolsTool; +use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\DeleteServerInstructionsTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ListServersTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\ShowServerInstructionsTool; use RefactorCircus\Cortex\Domains\ConcreteServer\Mcp\Tools\UpdateServerToolsTool; @@ -164,6 +165,55 @@ function mcpParityServerRow(): ?array }); }); +describe('delete-server-instructions-tool (D-057)', function (): void { + it('answers text when the row goes with its instructions', function (): void { + $this->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Published.', 'publish' => true])->assertCreated(); + + $response = mcpTool(DeleteServerInstructionsTool::class, ['server' => 'grouped']) + ->assertOk() + ->assertSee('Server instructions override deleted.'); + + /** @var array{result?: array} $payload */ + $payload = (fn (): array => $this->response->toArray())->call($response); + + expect($payload['result'] ?? [])->not->toHaveKey('structuredContent') + ->and(McpInstructionModel::query()->count())->toBe(0); + }); + + it('answers the surviving row as structured content, with parity to the HTTP route', function (): void { + $this->freezeTime(); + + $prepare = function (): void { + McpInstructionModel::query()->delete(); + + $this->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Published.', 'publish' => true])->assertCreated(); + $this->putJson(route('cortex.servers.tools.update', 'grouped'), ['tools' => ['echo-mcp-tool', 'renamed-echo']])->assertOk(); + app()->forgetScopedInstances(); + }; + + $prepare(); + $http = $this->deleteJson(route('cortex.servers.instructions.destroy', 'grouped'))->assertOk()->json('data'); + $httpRow = mcpParityServerRow(); + + expect($http)->toMatchArray([ + 'server' => 'grouped', + 'published_version' => null, + 'tools' => ['echo-mcp-tool', 'renamed-echo'], + 'tools_overridden' => true, + ]); + + $prepare(); + + // mcpTool() checks the structured answer against the tool's outputSchema(). + mcpTool(DeleteServerInstructionsTool::class, ['server' => 'grouped']) + ->assertOk() + ->assertStructuredContent(['data' => $http]); + + expect(mcpParityServerRow())->toBe($httpRow) + ->and($httpRow)->toBe(['tools' => ['echo-mcp-tool', 'renamed-echo'], 'published_version' => null, 'versions' => []]); + }); +}); + it('refuses both tools under a policy without updateTools, keeping the stored list', function (): void { mcpTool(UpdateServerToolsTool::class, ['server' => 'grouped', 'tools' => ['echo-mcp-tool']])->assertOk(); diff --git a/tests/Feature/ToolOnlyRowTest.php b/tests/Feature/ToolOnlyRowTest.php index 247de1f..f059d0b 100644 --- a/tests/Feature/ToolOnlyRowTest.php +++ b/tests/Feature/ToolOnlyRowTest.php @@ -32,7 +32,9 @@ 'left by deleting the instructions' => [function (): void { test()->postJson(route('cortex.servers.instructions.versions.store', 'grouped'), ['content' => 'Gone soon.', 'publish' => true])->assertCreated(); app(UpdateConcreteServerToolsAction::class)->execute('grouped', new UpdateConcreteServerToolsData(['echo-mcp-tool'])); - test()->deleteJson(route('cortex.servers.instructions.destroy', 'grouped'))->assertSuccessful(); + test()->deleteJson(route('cortex.servers.instructions.destroy', 'grouped')) + ->assertOk() + ->assertJsonPath('data.tools_overridden', true); }], ]); From 034150a726a0b811e0e429255f61a86f5fb71f24 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Sun, 25 Oct 2026 00:27:04 -0400 Subject: [PATCH 12/15] 2026-10-23-1917-virtual-and-concrete-mcp-servers: group 7 Atrium tool override editor Co-Authored-By: Claude Opus 5.5 (1M context) --- lang/en/cortex.php | 13 + .../views/ui/servers/instructions.blade.php | 9 + .../views/ui/servers/partials/tools.blade.php | 75 +++++ src/Atrium/CortexPlugin.php | 2 + .../McpInstructionUiController.php | 132 ++++++++ tests/Feature/Ui/ServerToolsEditorTest.php | 308 ++++++++++++++++++ 6 files changed, 539 insertions(+) create mode 100644 resources/views/ui/servers/partials/tools.blade.php create mode 100644 tests/Feature/Ui/ServerToolsEditorTest.php diff --git a/lang/en/cortex.php b/lang/en/cortex.php index fd4d40a..620153b 100644 --- a/lang/en/cortex.php +++ b/lang/en/cortex.php @@ -117,6 +117,19 @@ 'back_to_tools' => 'Back to tools', 'back_to_servers' => 'Back to servers', + // Server tool override + 'server_tools_override_hint' => 'The server serves the checked tools instead of those it declares in code. Tools already saved keep their order; newly checked ones are added in the order listed.', + 'server_tools_no_override_hint' => 'No override exists, so the server serves the tools it declares in code. Saving the checked tools creates one.', + 'server_tools_read_only_hint' => 'The tools this server serves.', + 'server_serves_no_tools' => 'This server serves no tools.', + 'unresolved' => 'unresolved', + 'confirm_empty_tools' => 'Serve no tools', + 'confirm_empty_tools_hint' => 'Required to save with no tool checked: the server then serves no tools at all.', + 'empty_tools_unconfirmed' => 'No tool is checked. Tick "Serve no tools" to save an empty list, or restore the code tools instead.', + 'restore_code_tools' => 'Restore code tools', + 'confirm_restore_code_tools' => 'Serve the tools declared in code again? The saved tool list is removed.', + 'code_tools_restored' => 'Code tools restored.', + // Redirect domains 'redirect_domains' => 'Redirect domains', 'redirect_domains_description' => 'Every origin MCP clients may register OAuth redirect URIs on: those in config, global ones added here, and those organizations and users add. Any client may register on any of them; each user still approves the client.', diff --git a/resources/views/ui/servers/instructions.blade.php b/resources/views/ui/servers/instructions.blade.php index 9eeeb29..3726d89 100644 --- a/resources/views/ui/servers/instructions.blade.php +++ b/resources/views/ui/servers/instructions.blade.php @@ -16,4 +16,13 @@ 'destroyRoute' => route('atrium.cortex.servers.instructions.destroy', $server), 'publishRoute' => fn (int $version) => route('atrium.cortex.servers.instructions.publish', [$server, $version]), ]) + + {{-- No tool editor for a server whose tools cannot be overridden (the cortex server). --}} + @if ($toolEditor !== null) + @include('cortex::ui.servers.partials.tools', [ + 'server' => $server, + 'subject' => $subject, + 'toolEditor' => $toolEditor, + ]) + @endif diff --git a/resources/views/ui/servers/partials/tools.blade.php b/resources/views/ui/servers/partials/tools.blade.php new file mode 100644 index 0000000..921c68c --- /dev/null +++ b/resources/views/ui/servers/partials/tools.blade.php @@ -0,0 +1,75 @@ +{{-- The tool override editor of a concrete server's screen. Expects $server, + $subject (the override, or an unsaved one, the policy is asked about) and + $toolEditor ({overridden, checked, served, items}); the screen leaves it + out for a server whose tools cannot be overridden. + + The save form posts `tools[]` (one checkbox per item, in checklist order), + `confirm_empty` and a `save` button; restoring the code tools is its own + form with a `restore` button. --}} +@php($mayUpdateTools = \RefactorCircus\Cortex\Atrium\ScreenAccess::allows('updateTools', $subject)) +@php($toolsError = ($errors ?? null)?->first('tools') ?: ($errors ?? null)?->first('tools.*') ?: ($errors ?? null)?->first('server')) + +
+ +
+ @if ($toolEditor['overridden']) + +

{{ __('cortex::cortex.server_tools_override_hint') }}

+ @else + +

{{ __('cortex::cortex.server_tools_no_override_hint') }}

+ @endif +
+ + @if ($toolsError) +
+ {{ $toolsError }} +
+ @endif + + @if (! $mayUpdateTools) + @if ($toolEditor['served'] === []) + + @else +
    + @foreach ($toolEditor['served'] as $tool) +
  • {{ $tool }}
  • + @endforeach +
+ @endif + @else +
+ @csrf + @method('PUT') + + @if ($toolEditor['items'] === []) + + @else + @include('cortex::ui.partials.tool-picker', [ + 'pickerTools' => $toolEditor['items'], + 'checked' => $toolEditor['checked'], + 'idPrefix' => 'server-tool-', + ]) + @endif + + + +
+ +
+ + + @if ($toolEditor['overridden']) +
+ @csrf + @method('DELETE') + + + @endif + @endif +
+
diff --git a/src/Atrium/CortexPlugin.php b/src/Atrium/CortexPlugin.php index 40114be..355224a 100644 --- a/src/Atrium/CortexPlugin.php +++ b/src/Atrium/CortexPlugin.php @@ -149,6 +149,8 @@ public function routes(): void Route::post('cortex/servers/{server}/instructions/versions/{version}/publish', [McpInstructionUiController::class, 'publish']) ->whereNumber('version')->name('servers.instructions.publish'); Route::delete('cortex/servers/{server}/instructions', [McpInstructionUiController::class, 'destroy'])->name('servers.instructions.destroy'); + Route::put('cortex/servers/{server}/tools', [McpInstructionUiController::class, 'updateTools'])->name('servers.tools.update'); + Route::delete('cortex/servers/{server}/tools', [McpInstructionUiController::class, 'clearTools'])->name('servers.tools.destroy'); Route::get('cortex/redirect-domains', [RedirectDomainUiController::class, 'index'])->name('redirect-domains.index'); Route::post('cortex/redirect-domains', [RedirectDomainUiController::class, 'store'])->name('redirect-domains.store'); diff --git a/src/Atrium/Http/Controllers/McpInstructionUiController.php b/src/Atrium/Http/Controllers/McpInstructionUiController.php index c6061d0..7ec35d2 100644 --- a/src/Atrium/Http/Controllers/McpInstructionUiController.php +++ b/src/Atrium/Http/Controllers/McpInstructionUiController.php @@ -7,15 +7,22 @@ use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Validation\ValidationException; use RefactorCircus\Cortex\Atrium\Http\Controllers\Concerns\AuthorizesScreens; use RefactorCircus\Cortex\Atrium\ScreenAccess; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\ClearConcreteServerToolsAction; use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\CreateMcpInstructionVersionAction; use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\DeleteMcpInstructionAction; use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\PublishMcpInstructionVersionAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Actions\UpdateConcreteServerToolsAction; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\ClearConcreteServerToolsData; use RefactorCircus\Cortex\Domains\ConcreteServer\Data\CreateMcpInstructionVersionData; +use RefactorCircus\Cortex\Domains\ConcreteServer\Data\UpdateConcreteServerToolsData; use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionVersionModel; use RefactorCircus\Cortex\Domains\ConcreteServer\Services\McpServerRegistry; +use RefactorCircus\Cortex\Domains\ConcreteServer\Services\ServerToolResolver; +use RefactorCircus\Cortex\Domains\Tool\Services\ToolRegistry; final class McpInstructionUiController { @@ -38,6 +45,7 @@ public function show(string $server): View 'instruction' => $instruction, 'subject' => ScreenAccess::serverInstruction($server, $instruction), 'versions' => $instruction?->versions()->chaperone('mcpInstruction')->orderByDesc('version')->get() ?? collect(), + 'toolEditor' => $this->toolEditor($server, $instruction), ]); } @@ -88,6 +96,56 @@ public function destroy(string $server): RedirectResponse ->with('status', __('cortex::cortex.override_removed')); } + /** + * Save the ticked tools as the server's tool override. Entries already + * stored keep their stored order and newly ticked ones follow in + * checklist order (the order the form posts them in). Saving with + * nothing ticked serves no tools at all, so it needs `confirm_empty`. + */ + public function updateTools(Request $request, string $server): RedirectResponse + { + $this->assertRegistered($server); + + $instruction = $this->override($server); + + $this->authorizeScreen('updateTools', ScreenAccess::serverInstruction($server, $instruction)); + + $selected = $request->input('tools', []); + + if (($selected === [] || $selected === null) && ! $request->boolean('confirm_empty')) { + throw ValidationException::withMessages([ + 'confirm_empty' => __('cortex::cortex.empty_tools_unconfirmed'), + ]); + } + + $data = UpdateConcreteServerToolsData::from( + array_merge($request->all(), ['tools' => $this->savedOrder($instruction?->tools, $selected ?? [])]), + $server, + ); + + app(UpdateConcreteServerToolsAction::class)->execute($server, $data); + + return redirect() + ->route('atrium.cortex.servers.instructions', $server) + ->with('status', __('cortex::cortex.tools_updated')); + } + + /** + * Clear the server's tool override, so it serves its code tools again. + */ + public function clearTools(Request $request, string $server): RedirectResponse + { + $this->assertRegistered($server); + + $this->authorizeScreen('updateTools', ScreenAccess::serverInstruction($server, $this->override($server))); + + app(ClearConcreteServerToolsAction::class)->execute($server, ClearConcreteServerToolsData::from($request->all(), $server)); + + return redirect() + ->route('atrium.cortex.servers.instructions', $server) + ->with('status', __('cortex::cortex.code_tools_restored')); + } + /** * The override row, or null when the server still uses the instructions it * declares in code. @@ -104,4 +162,78 @@ private function assertRegistered(string $server): void { abort_unless(app(McpServerRegistry::class)->has($server), 404); } + + /** + * What the tool editor shows, or null for a server whose tools cannot be + * overridden (the `cortex` server), which gets no editor at all. + * + * The checklist holds the server's code tools in code order, then the + * registered Cortex tools in registry order, then the stored entries that + * no longer resolve, each marked as unresolved. An item is checked when + * it is in the stored list, or, with no tool override, when the server + * declares it in code (what it serves now). `served` is what the server + * serves, for a viewer who may not change it. + * + * @return array{overridden: bool, checked: list, served: list, items: list}>}|null + */ + private function toolEditor(string $server, ?McpInstructionModel $instruction): ?array + { + $servers = app(McpServerRegistry::class); + + if (! $servers->supportsToolOverrides($server)) { + return null; + } + + $stored = $instruction?->tools; + $stored = is_array($stored) ? array_values(array_filter($stored, is_string(...))) : null; + + $report = app(ServerToolResolver::class)->report($server, $stored); + $code = $servers->defaultTools($server); + $registry = app(ToolRegistry::class); + + $items = []; + + foreach ([...$code, ...$registry->names()] as $name) { + $items[$name] ??= [ + 'name' => $name, + 'label' => $name, + 'tags' => $registry->has($name) ? $registry->tagsFor($name) : [], + ]; + } + + foreach ($report['missing_tools'] as $name) { + $items[$name] = [ + 'name' => $name, + 'label' => $name.' ('.__('cortex::cortex.unresolved').')', + 'tags' => $items[$name]['tags'] ?? [], + ]; + } + + return [ + 'overridden' => $report['tools_overridden'], + 'checked' => $stored ?? $code, + 'served' => $report['tools'], + 'items' => array_values($items), + ]; + } + + /** + * The ticked tools in saved order: the stored entries still ticked, in + * stored order, then the newly ticked ones in the order posted. Input + * that is not a list is passed on as is, for validation to refuse. + */ + private function savedOrder(mixed $stored, mixed $selected): mixed + { + if (! is_array($selected)) { + return $selected; + } + + $selected = array_values($selected); + $stored = is_array($stored) ? array_values($stored) : []; + + return [ + ...array_values(array_filter($stored, fn (mixed $entry): bool => in_array($entry, $selected, true))), + ...array_values(array_filter($selected, fn (mixed $entry): bool => ! in_array($entry, $stored, true))), + ]; + } } diff --git a/tests/Feature/Ui/ServerToolsEditorTest.php b/tests/Feature/Ui/ServerToolsEditorTest.php new file mode 100644 index 0000000..bdeb3e0 --- /dev/null +++ b/tests/Feature/Ui/ServerToolsEditorTest.php @@ -0,0 +1,308 @@ + true); + app()->detectEnvironment(fn (): string => 'local'); + + Cache::store('array')->flush(); + + app(McpServerRegistry::class)->register('grouped', GroupedToolsServer::class); + app(ToolRegistry::class)->register('echo-cortex-tool', EchoCortexTool::class); +}); + +/** + * Write the server's stored tool list directly, for values the update + * action refuses (a stale entry), then start a new request. + */ +function writeEditorServerTools(string $server, mixed $tools): void +{ + McpInstructionModel::query()->updateOrCreate(['server' => $server], ['tools' => null]); + + DB::table(Tables::name('mcp_instructions'))->where('server', $server)->update([ + 'tools' => $tools === null ? null : json_encode($tools, JSON_THROW_ON_ERROR), + ]); + + $cache = app(PublicationCache::class); + $cache->forget($cache->mcpToolsKey(), $cache->mcpInstructionsKey()); + + app()->forgetScopedInstances(); +} + +/** + * @return list|null + */ +function storedEditorServerTools(string $server): ?array +{ + app()->forgetScopedInstances(); + + /** @var list|null */ + return McpInstructionModel::query()->where('server', $server)->first()?->tools; +} + +/** + * Every `tools[]` checkbox on the page, in page order: its value, whether it + * is checked, and the text of its label. + * + * @return list + */ +function editorCheckboxes(TestResponse $response): array +{ + $html = (string) $response->getContent(); + + preg_match_all('/]*>/s', $html, $inputs); + + $boxes = []; + + foreach ($inputs[0] as $input) { + if (! str_contains($input, 'name="tools[]"')) { + continue; + } + + preg_match('/\bid="([^"]*)"/', $input, $id); + preg_match('/\bvalue="([^"]*)"/', $input, $value); + preg_match('/