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/AGENTS.md b/AGENTS.md index d48fda0..b09a58f 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 @@ -51,3 +51,11 @@ Atrium owns every component and style; Cortex ships no `resources/css`, no `Atri - `package-release`: use when preparing changelog, release notes, tags, or GitHub release workflow changes. - `package-compatibility`: use when reviewing code, dependencies, or CI against the PHP and Laravel support matrix. - `package-generate-skill`: use when updating the bundled Boost skill from the package implementation, README, and examples. + + +## Ring Master + +- Specs, product docs and local standards live in `docs/agent/`. Shared standards come from `vendor/` through `docs/agent/standards.index.yml`; read the matching standards before changing code. +- Workflow: `/ring-master-shape-spec` → `/ring-master-write-spec` → `/ring-master-create-tasks` → `/ring-master-implement` → `/ring-master-verify-spec`. +- Done means `vendor/bin/pest` passes. When work must break a standard, add a row to `docs/agent/standards-feedback.md`. + diff --git a/CHANGELOG.md b/CHANGELOG.md index f3297fd..ecdf7d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,29 @@ ## [Unreleased](https://github.com/Refactor-Circus/Cortex/commits/main) +### Upgrade notes (security-relevant) + +- **New routes and MCP tools that change an MCP server's tool list are live as soon as you upgrade.** `PUT /cortex/servers/{server}/tools`, `DELETE /cortex/servers/{server}/tools`, the `update-server-tools-tool` and `clear-server-tools-tool` MCP tools and the dashboard's tool editor check the new `updateTools` ability, and the bundled `McpInstructionPolicy` allows it **for guests too**, like every other bundled ability. The routes share the existing server routes' group and middleware, with no switch of their own. Whoever passes `updateTools` can put any registered Cortex tool (`Laravel\Ai` tools included) on a registered server, in front of every MCP client of that server; no per-tool ability is checked. Before deploying, point `McpInstructionModel` in `cortex.policies` at a policy whose `updateTools` denies by default (snippet in the README, "Who may change a server's tools") or make sure your route middleware keeps guests out. Outside the `local` environment Cortex logs a warning at boot, once per worker process, naming the servers whose tools guests may change. +- A host policy for `McpInstructionModel` that has no `updateTools` method denies it (the Gate's default): the tool routes answer 403 to a signed-in user and 401 to a guest, the MCP tools refuse and the dashboard shows the tools read-only. Add the method to use the feature. +- **Run the new migration.** Tool overrides live in a new nullable `tools` column on `cortex_mcp_instructions` (`2026_10_23_000002_add_tools_to_cortex_mcp_instructions`). Publish the migrations with `php artisan vendor:publish --tag="cortex-migrations"` and run `php artisan migrate`. If you already published Cortex's migrations, copy just that file from `vendor/refactor-circus/cortex/database/migrations` instead of publishing the tag again, which re-stamps every migration and makes `migrate` fail on existing tables; the migration skips a column that already exists. Until it runs, servers serve their code tools and Cortex logs a rate-limited warning naming the migration. The column check is remembered per process, so restart Octane and queue workers after migrating. Rolling the migration back drops the column and every stored tool override. +- **Run `composer dump-autoload -o`** after updating (and regenerate any pre-built or classmap-authoritative `vendor/`): the deprecated aliases of the renamed classes load through a new `autoload.files` entry, and without it the old class names are not found. +- **Drain your queues and re-register listeners** before upgrading: events, actions, Data objects, requests and exceptions of the old `Domains\McpServer` namespace moved without aliases (see Breaking). + ### Breaking +- **The `McpServer` domain is now `ConcreteServer`.** Every class moved from `RefactorCircus\Cortex\Domains\McpServer\...` to `RefactorCircus\Cortex\Domains\ConcreteServer\...` with its name unchanged, and `McpServerServiceProvider` is now `ConcreteServerServiceProvider`. Table names, route URIs and names, MCP tool names, config keys and registered server names are unchanged. Polymorphic columns and audit entries keep storing the old model class names, which a morph map resolves to the new models; a host that calls `Relation::enforceMorphMap()` or `Relation::morphMap([...], false)` must keep the two `Domains\McpServer\Models\...` keys, and must not map the two models under another alias. Cortex logs a warning after boot when either key is lost or re-mapped. +- **Events, actions, Data objects, requests and exceptions moved without aliases.** Only the classes listed under Deprecated keep their old names. A listener registered by an old event class name (`Event::listen`, a subscriber, a `$listen` map) stops hearing the event without an error, a `catch` of an old exception stops matching, a type-hint or binding of an old action breaks, and queued jobs or listeners serialized with an old class name fail to unserialize. Re-register listeners by the new class names and drain queues before upgrading. Asking for one of these old names logs a warning naming its new class, then fails as class not found. +- **`DELETE /cortex/servers/{server}/instructions` and `delete-server-instructions-tool` keep a tool override.** They delete the instruction versions and the published pointer, and remove the override row only when it holds no tool override. When there is none the answer is as before: 204 and a text answer over MCP. When the server has a tool override the row stays and the tools are still served, and the route now answers **200 with the server's instructions resource** (`tools_overridden: true`), the MCP tool that resource as structured content. Clear the tools with the new `DELETE /cortex/servers/{server}/tools`. The versions are deleted one model at a time, so each fires its own `McpInstructionVersionDeleting/DeletedEvent` (at least once: they fire inside the transaction, so a rolled-back delete has already fired them) and a long history means as many deletes in one transaction. With refactor-circus/keen installed the delete writes one `mcp_instruction.deleted` audit entry; the per-version deletes show only as model events. + - Moved to the Refactor Circus organisation: the package is now `refactor-circus/cortex` with the PHP namespace `RefactorCircus\Cortex` (it was `jayi/cortex` and `JayI\Cortex`). Update `composer.json` requirements and `use` statements. Old class names are not kept as aliases, so stored values written under them - polymorphic `*_type` columns, audit subjects, Pennant feature names - need updating to the new names. - **Actions take their input as Data objects instead of arrays.** Every Action that took an input array, a toolset list, a run input, a tag or a page now takes a typed, immutable `{Action}Data` from its domain's `Data` namespace, built on refactor-circus/keystone's `Data`: `CreateVirtualAgentData`, `UpdateVirtualAgentData`, `CreateVirtualAgentVersionData`, `ListVirtualAgentsData`, `ListVirtualAgentVersionsData`, `RunVirtualAgentData`, `CreateConcreteAgentVersionData`, `UpdateConcreteAgentToolsData`, `RunConcreteAgentData`, `CreateToolDescriptionVersionData`, `ListToolsData`, `CreateMcpInstructionVersionData` and `CreateRedirectDomainData`. Build one from untrusted input with `XData::from($input)`, which validates it (throwing `ValidationException`) and casts each snake_case key to its typed field; from input already validated against `XData::rules()` with `XData::fromValidated($validated)`; from your own values with `new XData(...)`, e.g. `app(CreateRedirectDomainAction::class)->execute(new CreateRedirectDomainData('claude.ai'), $owner)`. `Action::rules()` moved to `XData::rules()` (`UpdateConcreteAgentToolsData::rules($agent)` keeps its agent argument), and Actions without input lost their empty `rules()`. `UpdateVirtualAgentData` leaves fields out as `Keystone\Data\Missing`, so a field set to null stays apart from one not sent. Action events that carried the input (`VirtualAgentCreatingActionEvent::$data`, `ConcreteAgentToolsUpdatingActionEvent::$tools`, `VirtualAgentsListingActionEvent::$page`, `ToolsListingActionEvent::$tag`, the running and ran events' `$input`, ...) carry the Data object as `$data` or `$filters`. - **Structured MCP answers carry the resource under `data`.** Tools that answer with one record (show, create, update, publish, run) now answer `{"data": {...}}`, as the JSON API does, instead of the bare record; lists keep their `data` envelope, and the paginated virtual agent and version lists add a `meta` with the page. +### Deprecated + +- The old names of `Support\Server`, `Concerns\HasVersionedInstructions`, `Models\McpInstructionModel`, `Models\McpInstructionVersionModel`, `Policies\McpInstructionPolicy` and `Policies\McpInstructionVersionPolicy` under `RefactorCircus\Cortex\Domains\McpServer\` still load, as aliases of the `ConcreteServer` classes registered lazily (only when an old name is asked for) through `src/Domains/ConcreteServer/shims.php` in `autoload.files`. They are removed in the next major release; move your references to `RefactorCircus\Cortex\Domains\ConcreteServer\...`. +- `cortex.policies` keys naming an old model class are moved to the new class, keeping your policy, with a deprecation warning per key; when both keys are listed the new one wins. Key the entries by the new model classes. + ### Changed - **MCP output schemas.** Every tool that answers with structured content declares an `outputSchema()`, built from its resource's new `schema()` (fields, types and nullability), so agents know the shape before calling. Every resource extends refactor-circus/keystone's `JsonResource` and answers MCP calls with `toStructuredResponse()`. @@ -19,6 +36,9 @@ ### Added +- **Concrete server tool overrides.** A registered MCP server's tool list can be replaced without a deploy, picked from its code-declared tools and the registered Cortex tools: `PUT /cortex/servers/{server}/tools` (`cortex.servers.tools.update`) and the `update-server-tools-tool` MCP tool set it, `DELETE /cortex/servers/{server}/tools` (`cortex.servers.tools.destroy`) and `clear-server-tools-tool` clear it, and the server screen has a checklist editor with a "restore code tools" button. Actions `UpdateConcreteServerToolsAction` and `ClearConcreteServerToolsAction` (Data `UpdateConcreteServerToolsData`, `ClearConcreteServerToolsData`; events `ConcreteServerTools{Updating,Updated,Clearing,Cleared}ActionEvent`). Clients are served exactly the stored list, in the stored order; `[]` serves no tools. Servers need `Support\Server` or the `HasCortexOverrides` trait (`HasVersionedInstructions` is the same trait under its old name). The `cortex` server cannot be overridden. Stale, failing and ambiguous entries are skipped or resolved to the code tool, logged, and reported in the new `missing_tools` / `ambiguous_tools` fields beside `tools` and `tools_overridden` on the server list and the instructions show. See the README, "Overriding a Concrete Server's Tools". +- New `cortex.mcp.warning_ttl` config key (default 3600 seconds): how long Cortex stays quiet about a server override it cannot serve as saved once it has logged it, per server and entry, across requests. +- `McpServerRegistry::defaultTools()` and `supportsToolOverrides()`. - **Configurable table names**: every table, the `virtual_agent_sub_agents` pivot included, is named under the new `cortex.tables` config key and read by the migrations, models, validation rules and queries through `Support\Tables`. Keys a published config leaves out keep their default. Every model already has a bundled policy in `cortex.policies`; an arch test now keeps it that way. - **OAuth redirect domains** managed at runtime instead of only through `mcp.redirect_domains` (`MCP_REDIRECT_DOMAINS`). Cortex keeps a `cortex_redirect_domains` table (new migration) and replaces laravel/mcp's dynamic client registration controller with one that also accepts every stored origin. Domains may belong to any model (an organization, a user) or to no one, and are managed from the new **Redirect domains** dashboard screen (the compiled list of config, global, organization and user domains, filterable by source, where global domains are added), the `/cortex/redirect-domains` API and the `list-redirect-domains-tool`, `create-redirect-domain-tool` and `delete-redirect-domain-tool` MCP tools. Hosts and redirect URLs are stored as their origin; only config can allow `*`. Switch it off with `cortex.redirect_domains.enabled`. `RedirectDomainModel` gets a policy in `cortex.policies` that allows everything, like the other bundled policies. - The package's section in Atrium's sidebar rail has its own icon (`cpu-chip`) and a fixed place in the rail. diff --git a/README.md b/README.md index 233aead..c35b862 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ AI orchestration for Laravel. Cortex manages **virtual agents, concrete agents, - **Virtual agents** are database records that combine their own versioned prompt, registered tools, provider/model settings, and other agents (virtual or concrete) as sub-agents. Prompt content is immutable per version and a published pointer decides what runs; roll back by publishing an older version. - **Concrete agents** are classes in your code. Register them with Cortex to list, run and attach them as sub-agents, and override their prompt (versioned, publishable) and toolset without a deploy. - **Tools** are PHP classes implementing `Laravel\Ai\Contracts\Tool` or extending `Laravel\Mcp\Server\Tool` (wrapped automatically), registered by name in the Cortex tool registry. Their descriptions can be overridden at runtime with versioned, publishable content. -- **MCP servers** registered with Cortex get the same treatment for their instructions: versioned, publishable overrides that replace the code-declared instructions served to MCP clients, manageable over HTTP, MCP, and the dashboard. +- **MCP servers** registered with Cortex (concrete servers: classes in your code) get the same treatment for their instructions: versioned, publishable overrides that replace the code-declared instructions served to MCP clients, manageable over HTTP, MCP, and the dashboard. Their tool list can be overridden too, picked from the server's own tools and the registered Cortex tools. Run either kind via the API, the dashboard, the MCP server, or the `Cortex` facade. @@ -102,6 +102,8 @@ Every API endpoint and MCP tool that touches a model checks it through the Gate, Cortex records have no owner, so the bundled policies allow everything and your middleware stays the gate, as before. Version policies defer to their virtual agent or override through the Gate: reading a version needs `view` on it, adding or publishing one needs `update`. Point a model at your own policy class in `cortex.policies` to restrict it. +Changing a concrete MCP server's tool list checks its own ability, `updateTools`, which the bundled policy allows for guests too. Read [who may change a server's tools](#who-may-change-a-servers-tools) before exposing the routes. + **Full guide:** [Policies](docs/policies.md). It covers what each endpoint and MCP tool checks, and how to replace a policy. ## Dashboard @@ -114,7 +116,7 @@ use Illuminate\Support\Facades\Gate; Gate::define('viewAtrium', fn ($user) => $user->is_admin); ``` -The dashboard covers virtual agents with their prompt versions, concrete agents with their prompt and toolset overrides, a run playground, the tool registry (filterable by tag) with a versioned description editor, and the MCP server registry with a versioned instructions editor. +The dashboard covers virtual agents with their prompt versions, concrete agents with their prompt and toolset overrides, a run playground, the tool registry (filterable by tag) with a versioned description editor, and the MCP server registry with a versioned instructions editor and a tool list editor. Atrium owns the path, the middleware and the authorization gate, so there is nothing to configure here beyond the single switch: @@ -244,7 +246,9 @@ Everything is available over the REST API (prefix `cortex` by default): | GET/POST | `/cortex/tools/{tool}/description/versions` | List / create immutable override versions | | POST | `/cortex/tools/{tool}/description/versions/{version}/publish` | Publish an override version | | GET | `/cortex/servers` | List registered MCP servers with their effective instructions | -| GET/DELETE | `/cortex/servers/{server}/instructions` | Show / remove the instruction override | +| GET/DELETE | `/cortex/servers/{server}/instructions` | Show / remove the instruction override (a tool override stays) | +| PUT | `/cortex/servers/{server}/tools` | Set the tool override with `{"tools": [...]}` | +| DELETE | `/cortex/servers/{server}/tools` | Clear the tool override and serve the code tools again | | GET/POST | `/cortex/servers/{server}/instructions/versions` | List / create immutable override versions | | POST | `/cortex/servers/{server}/instructions/versions/{version}/publish` | Publish an override version | | GET/POST | `/cortex/redirect-domains` | List (optionally one owner's, with `owner_type` and `owner_id`) / add OAuth redirect domains | @@ -296,13 +300,13 @@ The dashboard's virtual agent form and `GET /cortex/providers` offer the same pr ## Publication Cache -Published virtual agent prompts, tool description overrides, MCP server instruction overrides, concrete agent overrides and the stored OAuth redirect domains are cached so agent runs, tool listings, and MCP handshakes don't hit the database on every request; publishing invalidates explicitly. When Redis is available it is preferred and read via `Cache::flexible()` using the `cache.fresh`/`cache.stale` windows (stale-while-revalidate); any other store caches until invalidation. Pin a store with `cache.store`, or set `cache.enabled` to `false` to read from the database on every pull. +Published virtual agent prompts, tool description overrides, MCP server instruction and tool overrides, concrete agent overrides and the stored OAuth redirect domains are cached so agent runs, tool listings, and MCP handshakes don't hit the database on every request; publishing invalidates explicitly. When Redis is available it is preferred and read via `Cache::flexible()` using the `cache.fresh`/`cache.stale` windows (stale-while-revalidate); any other store caches until invalidation. Pin a store with `cache.store`, or set `cache.enabled` to `false` to read from the database on every pull. On Redis, a publish clears the cached key, but a read or a `flexible()` background refresh already under way can write the previous content back; the stale value then lives until its `cache.fresh` window ends, so a publish can take up to `cache.fresh` seconds (300 by default) to reach every worker. Lower `cache.fresh`, or pin a non-Redis store with `cache.store`, where publishes must show immediately. ## MCP Server -The `CortexServer` exposes the virtual agent, concrete agent, tool, and server-instruction operations as MCP tools (29 tools: virtual agent CRUD + run + prompt versions + publish, concrete agent list/show/run + prompt versions + publish + tools + remove overrides, list tools, server instructions + versions + publish, OAuth redirect domains list/add/remove, and `list-cortex-history-tool` for the audit history). The provider and tool-description endpoints are HTTP-only. Enable a transport in the config: +The `CortexServer` exposes the virtual agent, concrete agent, tool, and server operations as MCP tools (31 tools: virtual agent CRUD + run + prompt versions + publish, concrete agent list/show/run + prompt versions + publish + tools + remove overrides, list tools, server instructions + versions + publish, server tool override set/clear, OAuth redirect domains list/add/remove, and `list-cortex-history-tool` for the audit history). The provider and tool-description endpoints are HTTP-only. Enable a transport in the config: ```php 'mcp' => [ @@ -332,7 +336,94 @@ use RefactorCircus\Cortex\Facades\Cortex; Cortex::servers()->register('support', \App\Mcp\SupportServer::class); ``` -For the published override to actually be served to MCP clients, the server class must extend `RefactorCircus\Cortex\Domains\McpServer\Support\Server` (or use the `RefactorCircus\Cortex\Domains\McpServer\Concerns\HasVersionedInstructions` trait if it cannot change its base class). Unregistered servers, and servers with no published version, keep serving their code-declared instructions. +For the published override to actually be served to MCP clients, the server class must extend `RefactorCircus\Cortex\Domains\ConcreteServer\Support\Server` (or use the `RefactorCircus\Cortex\Domains\ConcreteServer\Concerns\HasCortexOverrides` trait if it cannot change its base class; `HasVersionedInstructions` beside it is the same trait under its old name). Unregistered servers, and servers with no published version, keep serving their code-declared instructions. + +The domain was called `McpServer` before. `RefactorCircus\Cortex\Domains\McpServer\Support\Server`, `...\Concerns\HasVersionedInstructions`, the two models (`...\Models\McpInstructionModel`, `...\Models\McpInstructionVersionModel`) and their two policies (`...\Policies\McpInstructionPolicy`, `...\Policies\McpInstructionVersionPolicy`) still load under their old names, as deprecated aliases of the `ConcreteServer` classes that go away in the next major release. See [Upgrading from the McpServer domain](#upgrading-from-the-mcpserver-domain). + +### Overriding a Concrete Server's Tools + +A concrete server is an MCP server class registered with Cortex. Its tool list can be replaced without a deploy, the way its instructions can: the override is a list of tool names, picked from the server's own code-declared tools and the registered Cortex tools, and every client of the server is then served exactly that list. It needs the same base class or trait as the instruction override. + +- **API:** `PUT /cortex/servers/{server}/tools` (route `cortex.servers.tools.update`) with `{"tools": ["lookup", "search"]}` sets the override. `DELETE /cortex/servers/{server}/tools` (route `cortex.servers.tools.destroy`) clears it, and the server serves its code tools again. +- **MCP:** the `update-server-tools-tool` and `clear-server-tools-tool` tools on `CortexServer`, with the same input. +- **Dashboard:** the server's screen has a checklist of the server's code tools (in code order), then the registered tools (in registry order), with a "restore code tools" button. Saving with nothing ticked serves no tools, so the form asks you to confirm it. +- **Code:** `app(UpdateConcreteServerToolsAction::class)->execute('support', UpdateConcreteServerToolsData::from(['tools' => ['lookup']], 'support'))`, and `ClearConcreteServerToolsAction` to clear. + +The server list and the instructions show report four fields: `tools` (the effective list), `tools_overridden`, `missing_tools` (stored entries that are not served) and `ambiguous_tools` (stored entries that match both a code tool and a registered tool). + +#### What gets served + +- **Names.** An entry names a code-declared tool by its `name()` first, otherwise a registered Cortex tool by its registered name. When both match, the code tool wins: the entry is listed in `ambiguous_tools` and a warning is logged. Two entries that resolve to the same served name are refused (422 on the later one). +- **Order.** The stored order is a promise: clients get `tools/list` in the order you saved, and the `tools` field reports the same order. The dashboard checklist has no reorder control: it keeps the stored order for entries already in the list and adds new ones in checklist order. Send an explicit order through the API. +- **Empty and null.** `[]` is a valid override that serves no tools at all; the API does not ask for confirmation. `null` (or no override) serves the code-declared tools. +- **Flat list.** A server whose code tools sit behind `ToolSearch` is served a flat list once overridden; the grouping is dropped. +- **Tools the server adds itself.** Tools a server adds in its constructor or `boot()` are served when an override names them. Validation, the `tools`/`missing_tools` fields and the dashboard checklist read the server's `$tools` default by reflection, though, so a server that builds its tools dynamically shows only that reflected list there: the update refuses a tool added at runtime, and a stored entry naming one is served but reported in `missing_tools`. +- **Gating.** A selected tool keeps its own gating. A tool whose `shouldRegister()` is false stays hidden from `tools/list` and `tools/call`, and a `Laravel\Ai` tool keeps its own eligibility check, which sees the MCP request and its user. +- **Removed tools.** A tool the override leaves out is not just hidden: `tools/call` for it fails as an unknown tool. +- **Stale and failing entries.** An entry that no longer resolves (a code tool removed from the class, a tool no longer registered) or whose tool throws while it is built is skipped, the rest is served, a warning is logged and the entry is reported in `missing_tools`. A stored value that is not a list counts as no override. Each warning is logged once per server and entry per `cortex.mcp.warning_ttl` seconds (default 3600). +- **The `cortex` server.** Cortex's own server is the only one that cannot be overridden: the update and clear answer 422, a stored row is ignored, and its dashboard screen has no tool editor. +- **Cortex's management tools are not selectable.** `update-server-tools-tool` and the other `CortexServer` tools are not in the tool registry, so an override cannot put them on a server. Registering them with `Cortex::tools()->register()` makes them selectable, and puts Cortex's management in front of that server's clients: that is your call and your responsibility. +- **No history of its own.** The tool list is not versioned: there are no versions and no publish step, and saving replaces the list. + +#### Who may change a server's tools + +Setting and clearing the override checks `updateTools` on the server's override, through the `McpInstructionModel` policy in `cortex.policies`. **The bundled policy allows it, for guests too**, like every other bundled ability. Whoever passes it can put any registered Cortex tool on the server, `Laravel\Ai` tools included, in front of every MCP client of that server, whatever that server's own transport auth. No per-tool ability is checked: `updateTools` is the trust boundary, so any role you grant it can expose any registered tool, including tools you restrict elsewhere. While guests are allowed, Cortex logs a warning when it boots outside the `local` environment (once per worker process, never in the console) naming the servers concerned. + +Deny it by default with your own policy: + +```php +use Illuminate\Contracts\Auth\Authenticatable; +use RefactorCircus\Cortex\Domains\ConcreteServer\Models\McpInstructionModel; +use RefactorCircus\Cortex\Domains\ConcreteServer\Policies\McpInstructionPolicy; + +class InstructionPolicy extends McpInstructionPolicy +{ + public function updateTools(?Authenticatable $user, McpInstructionModel $instruction): bool + { + if ($user === null) { + return false; + } + + return $user->can('manage-mcp-tools'); + } +} + +// config/cortex.php +'policies' => [ + McpInstructionModel::class => InstructionPolicy::class, + // ... +], +``` + +A policy of your own that has no `updateTools` method denies it (the Gate's default): the routes answer 403 to a signed-in user and 401 to a guest, the MCP tools refuse, and the dashboard shows the server's tools read-only. Add the method when you want the feature. + +#### Deleting instructions keeps the tool override + +`DELETE /cortex/servers/{server}/instructions` and `delete-server-instructions-tool` clear the instructions only. They delete the versions and the published pointer, and remove the override row only when it holds no tool override: + +- with no tool override the row goes, and the answer is unchanged: 204, and a text answer over MCP; +- with a tool override the row stays, the tools are still served, and the answer is the server's instructions resource (200, structured content over MCP) showing `tools_overridden: true`. Clear the tools with `DELETE /cortex/servers/{server}/tools`. + +Before this release the delete always removed the whole override row. + +The versions are deleted one model at a time, so each fires its own `McpInstructionVersionDeletingEvent` / `McpInstructionVersionDeletedEvent`, and a long history means as many deletes inside one transaction. With refactor-circus/keen installed the delete writes one `mcp_instruction.deleted` audit entry for the whole delete; the per-version deletes show only as model events. Model events fire inside the transaction, so when it rolls back (a listener throws on a later version) the events of the versions already deleted have fired though the rows come back: treat those delete events as at-least-once. + +#### Caching and revocation + +The tool overrides are read through the [publication cache](#publication-cache) and forgotten after the write commits. Use a cache store that every node shares: a per-node store (`array`, `file`) never sees another node's invalidation and keeps serving the old list there. + +A cleared or changed list is served from the next request on a non-Redis store. On Redis a read or background refresh already under way can write the previous list back, so revoking a tool can take up to `cortex.cache.fresh` seconds (300 by default) to reach every worker; lower it, or pin a non-Redis store, where revocation must be immediate. If the cache store fails while forgetting, the change is still saved and the failure is logged, but the old list is served until the next successful invalidation (or, on Redis, until its stale window ends). + +The update, clear and delete re-read the override row with `lockForUpdate()` inside their transaction, so a tools save and an instructions delete never lose each other's write. The suite proves this on SQLite only, where the lock is a no-op; on MySQL and PostgreSQL the lock is expected to hold but is untested. + +#### Upgrading from the McpServer domain + +- **Run the new migration.** The override lives in a new nullable `tools` column on `cortex_mcp_instructions` (`2026_10_23_000002_add_tools_to_cortex_mcp_instructions.php`). If you never published Cortex's migrations, run `php artisan vendor:publish --tag="cortex-migrations"` and `php artisan migrate`. If you did, copy just that file from `vendor/refactor-circus/cortex/database/migrations` into `database/migrations` instead of publishing the tag again: publishing re-stamps every Cortex migration with a new timestamp, and `migrate` then fails on tables that already exist. The migration checks for the column first, so running it twice does nothing. Until it runs, servers serve their code tools (instructions overrides still apply) and Cortex logs a warning naming the migration. The column check is remembered per process, so restart Octane and queue workers after migrating. +- **Rolling back drops the tool overrides.** `migrate:rollback` of that migration drops the `tools` column and every stored tool override with it. +- **Renamed classes.** Classes moved from `RefactorCircus\Cortex\Domains\McpServer\...` to `RefactorCircus\Cortex\Domains\ConcreteServer\...`, names unchanged; `McpServerServiceProvider` is now `ConcreteServerServiceProvider`. Table names, route URIs and names, MCP tool names, config keys and server names are unchanged. +- **Deprecated aliases.** The old base class, trait, models and policies (listed under [Server Instruction Overrides](#server-instruction-overrides)) still load under their old names through a Composer `autoload.files` entry, so run `composer dump-autoload -o` after updating, and regenerate a pre-built or classmap-authoritative `vendor/`, or the old names are not found. A `cortex.policies` key that names an old model class is moved to the new class with a deprecation warning; key it by the new class. Move your references to the new names before the next major release. +- **Everything else moved without an alias.** Events, actions, Data objects, requests and exceptions of the old namespace have no alias. Asking for one logs a warning naming its new class, then fails as class not found. A listener registered by an old event class name (`Event::listen`, a subscriber, a `$listen` map) stops hearing the event silently, a `catch` of an old exception stops matching, and queued jobs or listeners serialized with an old class name fail to unserialize. Drain your queues before upgrading and re-register listeners by the new class names. +- **Keep the morph map keys.** Polymorphic columns and audit entries of the two models store, and keep storing, their old class names `RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionModel` and `RefactorCircus\Cortex\Domains\McpServer\Models\McpInstructionVersionModel`, which Cortex maps to the new classes in `Relation::morphMap()`. If you call `Relation::enforceMorphMap()` or `Relation::morphMap([...], false)`, keep those two keys, or stored rows stop resolving. Do not map the two model classes under another alias either: the new alias would win for writes and stored rows would mix two strings. Cortex logs a warning after boot when either happens. ### OAuth Redirect Domains 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/config/cortex.php b/config/cortex.php index d2250c6..fe31455 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; @@ -56,6 +56,24 @@ | 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 + | (README: "Who may change a server's tools"): + | + | public function updateTools(?Authenticatable $user, McpInstructionModel $instruction): bool + | { + | if ($user === null) { + | return false; + | } + | + | return $user->can('manage-mcp-tools'); + | } + | */ 'policies' => [ @@ -156,7 +174,9 @@ | | The `servers` list holds MCP server classes whose instructions Cortex | manages (versioned overrides replacing the code-declared value when - | published). Cortex's own server is always registered as 'cortex'. + | published) and whose tool list it can override (see the updateTools + | ability under Policies). Cortex's own server is always registered as + | 'cortex', and its tools cannot be overridden. | String keys set the server's registered name; unkeyed entries | derive it from the class. Servers may also be registered at | runtime via Cortex::servers()->register($name, $class). @@ -176,6 +196,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/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/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/docs/agent/standards/cortex/domains.md b/docs/agent/standards/cortex/domains.md new file mode 100644 index 0000000..9cc981a --- /dev/null +++ b/docs/agent/standards/cortex/domains.md @@ -0,0 +1,34 @@ +--- +description: "Cortex's domains (VirtualAgent, ConcreteAgent, Tool, ConcreteServer, RedirectDomain), its Mcp/{Tools,Requests} domain subdirectory, top-level package-wide classes, src/Atrium, and the stored names it must keep." +tags: [cortex, domains, layout, mcp, atrium] +kind: architectural +--- +# Cortex Domains + +Complements [[domain-modules]]: this is the list of Cortex's domains and the Cortex-only additions to the layout. + +## Domains + +- `VirtualAgent`: virtual agents, their versions, runtime and providers. +- `ConcreteAgent`: class-based agents, their registry and overrides. +- `Tool`: the tool registry and tool description overrides. +- `ConcreteServer`: class-based (concrete) MCP servers, their registry, instruction overrides and tool overrides. It was called `McpServer`; its class stems (`McpInstruction*`, `McpServer*`) keep that name, and only the namespace and `ConcreteServerServiceProvider` changed. +- `RedirectDomain`: stored OAuth redirect domains and the dynamic client registration controller that accepts them. + +## Extra domain subdirectory + +- `Mcp/{Tools,Requests}/` holds a domain's MCP tools and their request classes; see [[mcp-model-binding]] and [[mcp-responses]]. +- MCP tools are named `{Verb}{Entity}Tool` (`CreateVirtualAgentTool`). + +## Top level + +- Package-wide: `Cortex`, `CortexServiceProvider`, `Facades\Cortex`, the base `Http\Request` and `Mcp\Request`, `Mcp\CortexServer`, `Mcp\Tools\ListCortexHistoryTool`, `Http\Resources\AgentRunResource`, and `Support\` (`PublicationCache`, `WarningLimiter`, `AiToolAsMcpTool`, `Policies\Policy`). +- The Atrium screens span every domain, so they live in `src/Atrium` (`CortexPlugin`, `ScreenAccess`, `RunnableAgents`, `Badges`, `Http\Controllers\*UiController`, `Features\CortexSupportFeature`); see [[atrium-screens]]. +- `CortexServiceProvider` also keeps the `Cortex` singleton, the Atrium plugin, the Cortex MCP server and the history route (`loadHistoryRoutes()`). + +## Stored names + +- The two `ConcreteServer` models keep their pre-rename class names (`RefactorCircus\Cortex\Domains\McpServer\Models\{Entity}`) as their morph aliases through `keepMorphAliases()` in `ConcreteServerServiceProvider`, so stored rows stay uniform. The other models are stored under their own class names. +- The pre-rename names of `Support\Server`, `Concerns\HasVersionedInstructions`, the two models and their two policies stay loadable through the lazy `ConcreteServer/shims.php` autoload fallback until the next major release. No other old name is aliased. +- `CortexSupportFeature` keeps its Pennant stored name, `RefactorCircus\Cortex\Features\CortexSupportFeature`, with Pennant's `#[Name]` attribute. +- Tools, servers and agents are stored by their registered names, never their class names. 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/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/boost/skills/cortex-development/SKILL.md b/resources/boost/skills/cortex-development/SKILL.md index 66c4a61..2f779cd 100644 --- a/resources/boost/skills/cortex-development/SKILL.md +++ b/resources/boost/skills/cortex-development/SKILL.md @@ -5,8 +5,8 @@ description: > virtual agents with versioned prompts, registered concrete (class-based) agents with overridable prompts and toolsets, a tool registry with versioned description overrides, and an MCP server registry with versioned - instruction overrides, exposed through a REST API, a prebuilt dashboard, - and an MCP server. + instruction overrides and tool list overrides, exposed through a REST API, + a prebuilt dashboard, and an MCP server. license: MIT metadata: author: Jay Fletcher @@ -92,7 +92,9 @@ Tag tools to group them in the dashboard and agent tool pickers: `Cortex::tools( To let a tool's description be overridden at runtime (versioned + published like agent prompts), extend `RefactorCircus\Cortex\Domains\Tool\Support\Tool` or use the `RefactorCircus\Cortex\Domains\Tool\Concerns\HasVersionedDescription` trait. Manage overrides from the dashboard or `/cortex/tools/{tool}/description` endpoints. -MCP server *instructions* work the same way. Cortex's own server is always registered as `cortex`; register app servers under `cortex.mcp.servers` config (string keys name them; unkeyed entries derive the name from `#[Name]` or the class basename) or at runtime with `Cortex::servers()->register('support', \App\Mcp\SupportServer::class)`. For published overrides to be served to MCP clients, the server must extend `RefactorCircus\Cortex\Domains\McpServer\Support\Server` or use the `RefactorCircus\Cortex\Domains\McpServer\Concerns\HasVersionedInstructions` trait. +MCP server *instructions* work the same way. Cortex's own server is always registered as `cortex`; register app servers under `cortex.mcp.servers` config (string keys name them; unkeyed entries derive the name from `#[Name]` or the class basename) or at runtime with `Cortex::servers()->register('support', \App\Mcp\SupportServer::class)`. For published overrides to be served to MCP clients, the server must extend `RefactorCircus\Cortex\Domains\ConcreteServer\Support\Server` or use the `RefactorCircus\Cortex\Domains\ConcreteServer\Concerns\HasCortexOverrides` trait. The old `Domains\McpServer\Support\Server` and `Concerns\HasVersionedInstructions` names still load as deprecated aliases (removed next major); write new code against `Domains\ConcreteServer`. + +A registered server's *tool list* can be overridden too: `PUT /cortex/servers/{server}/tools` `{tools: [...]}` or the `update-server-tools-tool` MCP tool stores a list of names (a code tool's `name()` first, otherwise a registered Cortex tool name; the code tool wins when both match), and clients get exactly that list in that order (`[]` serves no tools). `DELETE /cortex/servers/{server}/tools` or `clear-server-tools-tool` restores the code tools. The `cortex` server cannot be overridden. Stale entries are skipped and reported in `missing_tools`. Both check the `updateTools` ability, which the bundled policy allows for guests: before exposing the routes, give `McpInstructionModel` a policy whose `updateTools` returns false for guests (and anyone you do not trust to put any registered tool in front of that server's clients). The tool override needs the `tools` column migration (`vendor:publish --tag="cortex-migrations"`, `migrate`). ### 5. Register concrete agents @@ -132,10 +134,11 @@ Register under `cortex.agents` config (string keys name them; unkeyed entries us - `GET /cortex/tools` — registered tools with JSON schemas. - `GET|DELETE /cortex/tools/{tool}/description`, `GET|POST .../description/versions`, `POST .../versions/{version}/publish` — versioned tool description overrides. - `GET /cortex/servers` — registered MCP servers with their effective instructions. -- `GET|DELETE /cortex/servers/{server}/instructions`, `GET|POST .../instructions/versions`, `POST .../versions/{version}/publish` — versioned server instruction overrides (rollback = publish an older version). +- `GET|DELETE /cortex/servers/{server}/instructions`, `GET|POST .../instructions/versions`, `POST .../versions/{version}/publish` — versioned server instruction overrides (rollback = publish an older version). The delete keeps a tool override (answering 200 with the instructions resource when one is kept, 204 otherwise). +- `PUT|DELETE /cortex/servers/{server}/tools` — set (`{tools: [...]}`) or clear a server's tool override; needs `updateTools`. - `GET /cortex/history` — Cortex's audit history, newest first (route `cortex.history.index`, from refactor-circus/keystone); answers 404 until an audit log such as refactor-circus/keen is installed. -The MCP server (`RefactorCircus\Cortex\Mcp\CortexServer`) exposes the virtual agent, concrete agent, tool-list, server-instruction and redirect-domain operations as 28 MCP tools, including `list-cortex-history-tool` (offered only while an audit log is installed and `cortex.audit.enabled` is on); the provider and tool-description endpoints are HTTP-only. Structured answers match the JSON API: the record under `data` (lists add `meta` when paginated), and every such tool declares an `outputSchema()`. A guest the policies refuse gets 401 over HTTP, a signed-in user 403; missing records answer `{"message": "Not found."}`. +The MCP server (`RefactorCircus\Cortex\Mcp\CortexServer`) exposes the virtual agent, concrete agent, tool-list, server-instruction, server-tool and redirect-domain operations as 31 MCP tools, including `update-server-tools-tool`, `clear-server-tools-tool` and `list-cortex-history-tool` (offered only while an audit log is installed and `cortex.audit.enabled` is on); the provider and tool-description endpoints are HTTP-only. Structured answers match the JSON API: the record under `data` (lists add `meta` when paginated), and every such tool declares an `outputSchema()`. A guest the policies refuse gets 401 over HTTP, a signed-in user 403; missing records answer `{"message": "Not found."}`. From code, call the Actions with their typed input (`RefactorCircus\Keystone\Data\Data` classes in each domain's `Data` namespace), never arrays: `app(CreateVirtualAgentAction::class)->execute(new CreateVirtualAgentData(name: 'Support', slug: 'support-agent', instructions: '...'))`, or `CreateVirtualAgentData::from($input)` to validate untrusted input first. `UpdateVirtualAgentData` changes only the fields given. Cortex stands on `refactor-circus/keystone`: its event contracts live in `RefactorCircus\Keystone\Contracts`. @@ -195,3 +198,4 @@ Read before executing: - do not edit prompt version content — versions are immutable; create a new version and publish it (concrete agent, tool description and server instruction override versions work the same way) - do not enable the MCP web transport or expose the routes without auth middleware, or ship the dashboard without a `viewAtrium` gate - do not attach tool class names to agents — attach the registered tool *names* from the registry +- do not leave `updateTools` open to guests in production, and do not register Cortex's own management tools in the tool registry unless every client of the servers you override may manage Cortex diff --git a/resources/views/ui/servers/instructions.blade.php b/resources/views/ui/servers/instructions.blade.php index dfc7303..3726d89 100644 --- a/resources/views/ui/servers/instructions.blade.php +++ b/resources/views/ui/servers/instructions.blade.php @@ -9,11 +9,20 @@ @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), '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 e0131e7..355224a 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; @@ -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 18e601c..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\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\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/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/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/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/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/ConcreteServer/Actions/DeleteMcpInstructionAction.php b/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php new file mode 100644 index 0000000..f9a8f3b --- /dev/null +++ b/src/Domains/ConcreteServer/Actions/DeleteMcpInstructionAction.php @@ -0,0 +1,87 @@ +perform($instruction); + + McpInstructionDeletedActionEvent::dispatch($instruction); + + return $surviving; + } + + private function perform(McpInstructionModel $instruction): ?McpInstructionModel + { + 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 */ + $locked = $instruction->newQuery()->whereKey($instruction->getKey())->lockForUpdate()->first(); + + if ($locked !== null) { + /** @var McpInstructionVersionModel $version */ + foreach ($locked->versions()->lazyById() as $version) { + $version->delete(); + } + + if ($locked->tools === null) { + $locked->delete(); + $locked = null; + } elseif ($locked->published_version_id !== null) { + $locked->published_version_id = null; + $locked->save(); + } + } + + DB::afterCommit(fn () => $this->forget($this->cache->mcpInstructionsKey(), $this->cache->mcpToolsKey())); + + return $locked; + }); + } + + /** + * 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/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/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/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 new file mode 100644 index 0000000..a64f95a --- /dev/null +++ b/src/Domains/ConcreteServer/Concerns/HasVersionedInstructions.php @@ -0,0 +1,15 @@ +> + */ + private const array OLD_MODEL_NAMES = [ + '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; + + /** + * 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); + + $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); + } + + public function boot(): void + { + $this->warnAboutOldPolicyKeys(); + + // Merges into the host's map (never replaces it, never enforces one). + $this->keepMorphAliases(self::OLD_MODEL_NAMES); + + // 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'); + } + + /** + * 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 + * 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::OLD_MODEL_NAMES 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/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/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/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 @@ +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/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/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/DeleteMcpInstructionRequest.php b/src/Domains/ConcreteServer/Http/Requests/DeleteMcpInstructionRequest.php new file mode 100644 index 0000000..0b03f52 --- /dev/null +++ b/src/Domains/ConcreteServer/Http/Requests/DeleteMcpInstructionRequest.php @@ -0,0 +1,33 @@ +allows('delete', $this->instruction()); + } + + /** + * 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 + { + $surviving = app(DeleteMcpInstructionAction::class)->execute($this->instruction()); + + if ($surviving === null) { + return response()->noContent(); + } + + return (new McpInstructionResource($surviving))->response()->setStatusCode(200); + } +} 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/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 new file mode 100644 index 0000000..86712c5 --- /dev/null +++ b/src/Domains/ConcreteServer/Http/Resources/McpServerResource.php @@ -0,0 +1,55 @@ + + */ + 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(), + ]; + } + + /** + * @return array + */ + public function toArray(Request $request): array + { + $name = $this->resource['name']; + + return [ + '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/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/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php b/src/Domains/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php new file mode 100644 index 0000000..84a0be0 --- /dev/null +++ b/src/Domains/ConcreteServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php @@ -0,0 +1,39 @@ +allows('delete', $this->instruction()); + } + + protected function rules(): array + { + return $this->serverRules(); + } + + /** + * 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 + { + $surviving = app(DeleteMcpInstructionAction::class)->execute($this->instruction()); + + if ($surviving === null) { + return Response::text('Server instructions override deleted.'); + } + + return (new McpInstructionResource($surviving))->toStructuredResponse(); + } +} 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/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/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 53% rename from src/Domains/McpServer/Mcp/Tools/DeleteServerInstructionsTool.php rename to src/Domains/ConcreteServer/Mcp/Tools/DeleteServerInstructionsTool.php index 7e335c4..fde09c3 100644 --- a/src/Domains/McpServer/Mcp/Tools/DeleteServerInstructionsTool.php +++ b/src/Domains/ConcreteServer/Mcp/Tools/DeleteServerInstructionsTool.php @@ -2,16 +2,17 @@ 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\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/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/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/McpServer/Models/McpInstructionModel.php b/src/Domains/ConcreteServer/Models/McpInstructionModel.php similarity index 73% rename from src/Domains/McpServer/Models/McpInstructionModel.php rename to src/Domains/ConcreteServer/Models/McpInstructionModel.php index 0dee3a4..684c8bb 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; @@ -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/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/ConcreteServer/Policies/McpInstructionPolicy.php b/src/Domains/ConcreteServer/Policies/McpInstructionPolicy.php new file mode 100644 index 0000000..9a7e0a4 --- /dev/null +++ b/src/Domains/ConcreteServer/Policies/McpInstructionPolicy.php @@ -0,0 +1,73 @@ +can(...)` for MCP server instruction overrides. + * + * Overrides have no owner, so every ability is allowed, for guests too: the route + * middleware in front of the API and MCP server decides who gets in. Point + * `cortex.policies` at your own class to restrict them. + */ +class McpInstructionPolicy extends Policy +{ + public function viewAny(?Authenticatable $user): bool + { + return true; + } + + public function create(?Authenticatable $user): bool + { + return true; + } + + public function view(?Authenticatable $user, McpInstructionModel $instruction): bool + { + return true; + } + + public function update(?Authenticatable $user, McpInstructionModel $instruction): bool + { + return true; + } + + public function delete(?Authenticatable $user, McpInstructionModel $instruction): bool + { + return true; + } + + /** + * Overriding or clearing the server's tool list (PUT and DELETE + * `cortex/servers/{server}/tools`, the `update-server-tools` and + * `clear-server-tools` MCP tools, the Atrium tool editor). Checked on the + * server's override, or an unsaved one naming the server when it has + * none. + * + * The bundled default allows it for guests too. This is the trust + * boundary for tools: no per-tool ability is checked, so whoever passes + * it can put any registered Cortex tool (`Laravel\Ai` tools included) on + * the server, in front of every MCP client of that server. Outside the + * `local` environment Cortex logs a warning at boot while guests are + * allowed. A host policy without this method denies it (the Gate's + * default). To allow signed-in users you trust only: + * + * public function updateTools(?Authenticatable $user, McpInstructionModel $instruction): bool + * { + * if ($user === null) { + * return false; + * } + * + * return $user->can('manage-mcp-tools'); + * } + */ + public function updateTools(?Authenticatable $user, McpInstructionModel $instruction): bool + { + return true; + } +} 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 60% rename from src/Domains/McpServer/Resources/McpInstructionResource.php rename to src/Domains/ConcreteServer/Resources/McpInstructionResource.php index 500c993..c4f236e 100644 --- a/src/Domains/McpServer/Resources/McpInstructionResource.php +++ b/src/Domains/ConcreteServer/Resources/McpInstructionResource.php @@ -2,15 +2,20 @@ 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\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/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/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/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 62% rename from src/Domains/McpServer/Services/McpServerRegistry.php rename to src/Domains/ConcreteServer/Services/McpServerRegistry.php index bfce432..91f782a 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,17 +10,24 @@ 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 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,55 @@ 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 + { + $names = []; + + foreach ($this->declaredTools($name) as $entry) { + foreach (is_array($entry) ? $entry : [$entry] as $tool) { + $names[] = $this->toolName($tool); + } + } + + 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 + * 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 +186,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 +196,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..22180a2 --- /dev/null +++ b/src/Domains/ConcreteServer/Services/McpToolOverrides.php @@ -0,0 +1,144 @@ +|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->hasToolsColumn($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(...))); + } + + /** + * 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. + * + * @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/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..d4a650e --- /dev/null +++ b/src/Domains/ConcreteServer/Services/ServerToolResolver.php @@ -0,0 +1,255 @@ +, 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 + * registered tool (D-021) are logged through the rate limit, once per + * call; the context memo makes that once per request. + * + * @param array $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 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, entries: list, missing: list, failed: array, ambiguous: list} + */ + public function resolve(array $codeTools, array $entries): array + { + $code = $this->codeTools($codeTools); + $registered = $this->registeredClasses(); + + $tools = []; + $servedEntries = []; + $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; + $servedEntries[] = $entry; + } + + return ['tools' => $tools, 'entries' => $servedEntries, '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/Services/ToolsColumn.php b/src/Domains/ConcreteServer/Services/ToolsColumn.php new file mode 100644 index 0000000..2b29e36 --- /dev/null +++ b/src/Domains/ConcreteServer/Services/ToolsColumn.php @@ -0,0 +1,38 @@ + + */ + 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/Domains/ConcreteServer/Support/Server.php b/src/Domains/ConcreteServer/Support/Server.php new file mode 100644 index 0000000..3a23b62 --- /dev/null +++ b/src/Domains/ConcreteServer/Support/Server.php @@ -0,0 +1,26 @@ +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/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/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/Domains/McpServer/Actions/DeleteMcpInstructionAction.php b/src/Domains/McpServer/Actions/DeleteMcpInstructionAction.php deleted file mode 100644 index 2062eb5..0000000 --- a/src/Domains/McpServer/Actions/DeleteMcpInstructionAction.php +++ /dev/null @@ -1,34 +0,0 @@ -perform($instruction); - - McpInstructionDeletedActionEvent::dispatch($instruction); - } - - private function perform(McpInstructionModel $instruction): void - { - DB::transaction(function () use ($instruction): void { - $instruction->delete(); - - DB::afterCommit(fn () => $this->cache->forget($this->cache->mcpInstructionsKey())); - }); - } -} diff --git a/src/Domains/McpServer/Concerns/HasVersionedInstructions.php b/src/Domains/McpServer/Concerns/HasVersionedInstructions.php deleted file mode 100644 index c23d252..0000000 --- a/src/Domains/McpServer/Concerns/HasVersionedInstructions.php +++ /dev/null @@ -1,38 +0,0 @@ -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; - } -} diff --git a/src/Domains/McpServer/Http/Requests/DeleteMcpInstructionRequest.php b/src/Domains/McpServer/Http/Requests/DeleteMcpInstructionRequest.php deleted file mode 100644 index a52bb43..0000000 --- a/src/Domains/McpServer/Http/Requests/DeleteMcpInstructionRequest.php +++ /dev/null @@ -1,23 +0,0 @@ -allows('delete', $this->instruction()); - } - - public function persist(): Response - { - app(DeleteMcpInstructionAction::class)->execute($this->instruction()); - - return response()->noContent(); - } -} diff --git a/src/Domains/McpServer/Http/Resources/McpServerResource.php b/src/Domains/McpServer/Http/Resources/McpServerResource.php deleted file mode 100644 index 91fae33..0000000 --- a/src/Domains/McpServer/Http/Resources/McpServerResource.php +++ /dev/null @@ -1,38 +0,0 @@ - - */ - public static function schema(JsonSchema $schema): array - { - return [ - 'name' => $schema->string()->required(), - 'instructions' => $schema->string()->required(), - ]; - } - - /** - * @return array - */ - public function toArray(Request $request): array - { - return [ - 'name' => $this->resource['name'], - 'instructions' => $this->resource['instructions'], - ]; - } -} diff --git a/src/Domains/McpServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php b/src/Domains/McpServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php deleted file mode 100644 index 6a7d866..0000000 --- a/src/Domains/McpServer/Mcp/Requests/DeleteServerInstructionsMcpRequest.php +++ /dev/null @@ -1,28 +0,0 @@ -allows('delete', $this->instruction()); - } - - protected function rules(): array - { - return $this->serverRules(); - } - - protected function handle(array $validated): Response - { - app(DeleteMcpInstructionAction::class)->execute($this->instruction()); - - return Response::text('Server instructions override deleted.'); - } -} diff --git a/src/Domains/McpServer/McpServerServiceProvider.php b/src/Domains/McpServer/McpServerServiceProvider.php deleted file mode 100644 index bdea1d3..0000000 --- a/src/Domains/McpServer/McpServerServiceProvider.php +++ /dev/null @@ -1,24 +0,0 @@ -app->singleton(McpServerRegistry::class); - - $this->app->scoped(McpInstructionOverrides::class); - } - - public function boot(): void - { - $this->loadApiRoutesFrom(__DIR__.'/routes.php'); - } -} diff --git a/src/Domains/McpServer/Support/Server.php b/src/Domains/McpServer/Support/Server.php deleted file mode 100644 index 81d260f..0000000 --- a/src/Domains/McpServer/Support/Server.php +++ /dev/null @@ -1,20 +0,0 @@ -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/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/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/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/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/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); + } +}); 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/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/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..16d0f4d --- /dev/null +++ b/tests/Feature/DeleteMcpInstructionActionTest.php @@ -0,0 +1,190 @@ +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): ?McpInstructionModel +{ + $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']); + + 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(); + + $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() + ->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/DocsTest.php b/tests/Feature/DocsTest.php new file mode 100644 index 0000000..74630ea --- /dev/null +++ b/tests/Feature/DocsTest.php @@ -0,0 +1,157 @@ +toBeTrue("{$path} is missing."); + + return (string) file_get_contents($file); +} + +/** + * The CHANGELOG's Unreleased section, up to the next release heading. + */ +function unreleasedChangelog(): string +{ + $changelog = packageDocument('CHANGELOG.md'); + + expect(preg_match('/^## \[Unreleased\].*?(?=^## \[)/ms', $changelog, $matches))->toBe(1, 'CHANGELOG.md has no Unreleased section.'); + + return $matches[0]; +} + +/** + * The fenced PHP blocks of a Markdown document. + * + * @return list + */ +function phpBlocks(string $markdown): array +{ + preg_match_all('/^```php\n(.*?)^```/ms', $markdown, $matches); + + return array_values($matches[1]); +} + +/** + * Whether a snippet denies `updateTools` by default: it defines the ability + * and returns false. + */ +function deniesUpdateToolsByDefault(string $snippet): bool +{ + return str_contains($snippet, 'function updateTools(') && str_contains($snippet, 'return false'); +} + +/** + * The comment block of `config/cortex.php` right before a key. + */ +function configBanner(string $key): string +{ + $config = packageDocument('config/cortex.php'); + $position = strpos($config, "'{$key}' =>"); + + expect($position)->not->toBeFalse("config/cortex.php has no '{$key}' key."); + + $before = substr($config, 0, (int) $position); + $start = strrpos($before, '/*'); + + expect($start)->not->toBeFalse("config/cortex.php has no banner before '{$key}'."); + + return substr($before, (int) $start); +} + +describe('README', function (): void { + it('names the update and clear routes, as they are registered', function (string $name, string $method): void { + $route = Route::getRoutes()->getByName($name); + + expect($route)->not->toBeNull() + ->and($route?->uri())->toBe('cortex/servers/{server}/tools') + ->and($route?->methods())->toContain($method) + ->and(packageDocument('README.md'))->toContain("{$method} /cortex/servers/{server}/tools") + ->toContain($name); + })->with([ + 'update' => ['cortex.servers.tools.update', 'PUT'], + 'clear' => ['cortex.servers.tools.destroy', 'DELETE'], + ]); + + it('names the update and clear MCP tools by the names they are served under', function (string $tool, string $stem): void { + $name = app($tool)->name(); + + expect($name)->toContain($stem) + ->and(packageDocument('README.md'))->toContain("`{$name}`"); + })->with([ + 'update' => [UpdateServerToolsTool::class, 'update-server-tools'], + 'clear' => [ClearServerToolsTool::class, 'clear-server-tools'], + ]); + + it('names the updateTools ability and carries a deny-by-default policy snippet', function (): void { + $readme = packageDocument('README.md'); + + expect($readme)->toContain('`updateTools`') + ->and(array_filter(phpBlocks($readme), deniesUpdateToolsByDefault(...)))->not->toBeEmpty('README.md has no PHP snippet whose updateTools returns false.'); + }); +}); + +it('mentions both server tool MCP tools in the Boost skill', function (): void { + expect(packageDocument('resources/boost/skills/cortex-development/SKILL.md')) + ->toContain('update-server-tools') + ->toContain('clear-server-tools'); +}); + +describe('CHANGELOG', function (): void { + it('keeps the upgrade keywords in the Unreleased section', function (string $keyword): void { + expect(unreleasedChangelog())->toContain($keyword); + })->with([ + 'optimized autoloader' => ['dump-autoload -o'], + 'publish the migrations' => ['vendor:publish'], + 'run them' => ['migrate'], + 'the ability' => ['updateTools'], + 'restart workers' => ['restart'], + ]); + + it('opens the Unreleased section with the updateTools upgrade note', function (): void { + expect(preg_match('/^### .*?(?=^### )/ms', unreleasedChangelog(), $first))->toBe(1) + ->and($first[0])->toContain('updateTools') + ->toContain('/cortex/servers/{server}/tools'); + }); +}); + +describe('config/cortex.php', function (): void { + it('documents the warning TTL in its own banner', function (): void { + $config = require dirname(__DIR__, 2).'/config/cortex.php'; + $banner = configBanner('warning_ttl'); + + expect($config['mcp']['warning_ttl'])->toBe(3600) + ->and($banner)->toContain('MCP Warning Rate Limit') + ->toContain('warning_ttl') + ->toContain('3600'); + }); + + it('names updateTools in the policies comment, with a deny-by-default snippet', function (): void { + $banner = configBanner('policies'); + + expect($banner)->toContain('updateTools') + ->toContain('guests') + ->and(deniesUpdateToolsByDefault($banner))->toBeTrue(); + }); +}); + +it('lists the ConcreteServer domain in the domains standard', function (): void { + expect(packageDocument('docs/agent/standards/cortex/domains.md'))->toContain('`ConcreteServer`'); +}); diff --git a/tests/Feature/EventsTest.php b/tests/Feature/EventsTest.php index 01e83dd..8146679 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; @@ -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/Feature/Http/ConcreteServerToolsTest.php b/tests/Feature/Http/ConcreteServerToolsTest.php new file mode 100644 index 0000000..528ebdc --- /dev/null +++ b/tests/Feature/Http/ConcreteServerToolsTest.php @@ -0,0 +1,355 @@ +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]); + }); +}); + +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')) + ->assertOk() + ->assertJsonPath('data.tools_overridden', true); + + 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/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/OutputSchemaTest.php b/tests/Feature/Mcp/OutputSchemaTest.php index 40c51b2..b53e6f7 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(27) ->and($missing)->toBe([]); }); 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/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/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/Feature/Mcp/ServerToolsToolsTest.php b/tests/Feature/Mcp/ServerToolsToolsTest.php new file mode 100644 index 0000000..56f7603 --- /dev/null +++ b/tests/Feature/Mcp/ServerToolsToolsTest.php @@ -0,0 +1,235 @@ +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.']); + }); +}); + +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(); + + 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/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/McpToolOverridesTest.php b/tests/Feature/McpToolOverridesTest.php new file mode 100644 index 0000000..ffd64ad --- /dev/null +++ b/tests/Feature/McpToolOverridesTest.php @@ -0,0 +1,416 @@ +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(); + }); +}); + +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); + + 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/ModelsTest.php b/tests/Feature/ModelsTest.php index 6866b25..3e9fa8c 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; @@ -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. ]); 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/ToolOnlyRowTest.php b/tests/Feature/ToolOnlyRowTest.php new file mode 100644 index 0000000..f059d0b --- /dev/null +++ b/tests/Feature/ToolOnlyRowTest.php @@ -0,0 +1,106 @@ +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')) + ->assertOk() + ->assertJsonPath('data.tools_overridden', true); + }], +]); + +/** + * 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'); 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/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/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('/