From 3842d8a4b64692087c59767e830fcb83020f13ac Mon Sep 17 00:00:00 2001 From: "middle:Sokil" Date: Wed, 18 Nov 2026 09:43:22 +0200 Subject: [PATCH 1/2] feat(emcp): consolidate the Evo toolset for version 2 --- .ci/governance-lock.json | 21 +- CHANGELOG.md | 6 + DOCS.md | 13 +- DOCS.uk.md | 13 +- OPERATIONS.md | 23 +- README.md | 4 +- README.uk.md | 4 +- SPEC.md | 27 +- TOOLSET.md | 89 ++++-- composer.json | 5 + config/eMCPSettings.php | 1 - scripts/demo_verify.sh | 16 +- scripts/governance_helpers.php | 5 + skills/evolution-cms-mcp/SKILL.md | 10 +- .../references/core-tools.md | 18 +- .../evolution-cms-mcp/references/workflows.md | 8 +- src/Console/Commands/eMcpTestCommand.php | 15 +- .../ToolArguments/ContentNodeListArgs.php | 21 -- .../ToolArguments/ContentNodeRangeArgs.php | 22 -- .../ToolArguments/ContentRootTreeArgs.php | 20 -- .../ToolResponses/ListToolResponse.php | 11 +- src/Http/Controllers/McpManagerController.php | 4 +- src/Servers/ContentServer.php | 21 +- src/Support/ToolContract.php | 57 ++++ src/Tools/Content/BaseContentTool.php | 99 +++++- src/Tools/Content/ContentAncestorsTool.php | 110 +++---- .../Content/ContentChildrenRangeTool.php | 122 ------- src/Tools/Content/ContentChildrenTool.php | 107 ------- src/Tools/Content/ContentDescendantsTool.php | 115 ------- src/Tools/Content/ContentGetTool.php | 19 +- src/Tools/Content/ContentNeighborsTool.php | 108 ------- src/Tools/Content/ContentNextSiblingsTool.php | 107 ------- src/Tools/Content/ContentPrevSiblingsTool.php | 107 ------- src/Tools/Content/ContentRootTreeTool.php | 108 ------- src/Tools/Content/ContentSearchTool.php | 46 ++- .../Content/ContentSiblingsRangeTool.php | 123 -------- src/Tools/Content/ContentSiblingsTool.php | 153 +++++---- src/Tools/Content/ContentTreeTool.php | 134 ++++++++ src/Tools/Elements/ElementsGetTool.php | 22 +- src/Tools/Elements/ElementsListTool.php | 28 +- src/Tools/ModelCatalog/BaseModelTool.php | 6 +- src/Tools/ModelCatalog/ModelGetTool.php | 22 +- src/Tools/ModelCatalog/ModelListTool.php | 37 ++- src/Tools/Write/BaseWriteTool.php | 4 +- src/Tools/Write/CacheClearTool.php | 16 +- src/Tools/Write/ContentCreateTool.php | 26 +- src/Tools/Write/ContentPublishTool.php | 26 +- src/Tools/Write/ContentUpdateTool.php | 96 ++++-- src/Tools/Write/ElementsSaveTool.php | 28 +- .../StreamingAndResultLimitsBehaviorTest.php | 4 +- tests/Fixtures/golden/evo_content_get.json | 2 +- tests/Fixtures/golden/evo_content_search.json | 2 +- tests/Fixtures/golden/initialize.json | 4 +- tests/Fixtures/golden/tools_list.json | 51 ++- .../ClosureTableInvariantsHttpTest.php | 24 +- .../RuntimeIntegrationHttpTest.php | 33 +- tests/Integration/ToolsetV2SqliteHttpTest.php | 298 ++++++++++++++++++ tests/Phase25/ContractsAndPipelineTest.php | 12 +- .../Phase6/AdvancedTreeToolsContractsTest.php | 64 +--- tests/Phase6/SiteContentContractsTest.php | 51 +-- tests/Unit/ToolDefinitionsTest.php | 75 +++++ 61 files changed, 1364 insertions(+), 1459 deletions(-) delete mode 100644 src/Contracts/ToolArguments/ContentNodeListArgs.php delete mode 100644 src/Contracts/ToolArguments/ContentNodeRangeArgs.php delete mode 100644 src/Contracts/ToolArguments/ContentRootTreeArgs.php create mode 100644 src/Support/ToolContract.php delete mode 100644 src/Tools/Content/ContentChildrenRangeTool.php delete mode 100644 src/Tools/Content/ContentChildrenTool.php delete mode 100644 src/Tools/Content/ContentDescendantsTool.php delete mode 100644 src/Tools/Content/ContentNeighborsTool.php delete mode 100644 src/Tools/Content/ContentNextSiblingsTool.php delete mode 100644 src/Tools/Content/ContentPrevSiblingsTool.php delete mode 100644 src/Tools/Content/ContentRootTreeTool.php delete mode 100644 src/Tools/Content/ContentSiblingsRangeTool.php create mode 100644 src/Tools/Content/ContentTreeTool.php create mode 100644 tests/Integration/ToolsetV2SqliteHttpTest.php create mode 100644 tests/Unit/ToolDefinitionsTest.php diff --git a/.ci/governance-lock.json b/.ci/governance-lock.json index b7d3a61..2a7e80c 100644 --- a/.ci/governance-lock.json +++ b/.ci/governance-lock.json @@ -1,20 +1,25 @@ { - "toolset_version": "1.0", + "toolset_version": "2.0", "canonical_tools": [ "evo.content.search", "evo.content.get", - "evo.content.root_tree", - "evo.content.descendants", + "evo.content.tree", "evo.content.ancestors", - "evo.content.children", "evo.content.siblings", "evo.model.list", - "evo.model.get" + "evo.model.get", + "evo.elements.list", + "evo.elements.get", + "evo.write.content.update", + "evo.write.content.create", + "evo.write.content.publish", + "evo.write.elements.save", + "evo.write.cache.clear" ], - "spec_version": "1.0-contract", + "spec_version": "2.0-contract", "runtime_status": "Gate C baseline validated in demo runtime; RC-1 hardening pending", "spec_public_contract_hash": "752772e83d65c41fe55bd6ddef3359a8ab04f0e3efe67d4901e79870d1967e7b", "model_allowlists_hash": "4aed463f34f34da8231a6499bd58bcc11755d0bdb9bb69f86d9610b51e92b42d", - "golden_fixtures_hash": "d015d5fdab8c8f2f5267cdf47046e6580c730edc7c50cc4515eb4dfd2265c147", - "updated_at": "2026-09-29T11:20:48+00:00" + "golden_fixtures_hash": "f00e4c054f00221cb2087bfaf9aafa32481b6c0d576672fde8556506d1536aea", + "updated_at": "2026-11-18T07:39:01+00:00" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d3ac30..91b3f9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased — Toolset 2.0 + +- Canonical tools: consolidated navigation into tree and siblings, with 14 Evo tools in discovery. +- Published input and output schemas now describe supported filters, TV projection and result envelopes. +- Document updates are atomic with TVs and explicitly enforce publication permissions. + ## [Unreleased] ### Added - Personal access tokens (`auth.mode = pat`, now the default): `emcp_tokens` table, `Authorization: Bearer emcp_...` endpoint at `/{api_prefix}/{server}` without sApi, self-service **Tools → MCP tokens** manager page, `emcp:token:create|list|revoke` commands. diff --git a/DOCS.md b/DOCS.md index aa574c9..3020a62 100644 --- a/DOCS.md +++ b/DOCS.md @@ -9,7 +9,7 @@ Contract boundary: - `OPERATIONS.md` is the day-2 operator runbook (profiles, health checks, triage). Status marker: -- Contract target: `SPEC 1.0-contract`. +- Contract target: `SPEC 2.0-contract`. - Runtime baseline in current repository: `Gate C baseline implemented (full validation pending)`. ## 1) Overview @@ -376,18 +376,11 @@ Canonical source for tool names/params/examples/errors is `TOOLSET.md`. Primary domain profile is document tree access via `SiteContent`: - `evo.content.search` - `evo.content.get` -- `evo.content.root_tree` -- `evo.content.descendants` +- `evo.content.tree` - `evo.content.ancestors` -- `evo.content.children` - `evo.content.siblings` -Optional (implemented) tree tools: -- `evo.content.neighbors` -- `evo.content.prev_siblings` -- `evo.content.next_siblings` -- `evo.content.children_range` -- `evo.content.siblings_range` +[Toolset 2.0 migration](TOOLSET.md#migration-from-toolset-10). TV support is part of the contract: - `with_tvs` maps to `withTVs` diff --git a/DOCS.uk.md b/DOCS.uk.md index 743b676..4d2e7c4 100644 --- a/DOCS.uk.md +++ b/DOCS.uk.md @@ -9,7 +9,7 @@ Contract boundary: - `OPERATIONS.md` є day-2 runbook для операторів (profiles, health checks, triage). Status marker: -- Цільовий контракт: `SPEC 1.0-contract`. +- Цільовий контракт: `SPEC 2.0-contract`. - Runtime baseline в поточному репозиторії: `Gate C baseline implemented (full validation pending)`. ## 1) Огляд @@ -376,18 +376,11 @@ tool задає сам, зберігаються). Це підказки для Головний доменний профіль: робота з деревом документів через `SiteContent`: - `evo.content.search` - `evo.content.get` -- `evo.content.root_tree` -- `evo.content.descendants` +- `evo.content.tree` - `evo.content.ancestors` -- `evo.content.children` - `evo.content.siblings` -Опційні (вже реалізовані) tree tools: -- `evo.content.neighbors` -- `evo.content.prev_siblings` -- `evo.content.next_siblings` -- `evo.content.children_range` -- `evo.content.siblings_range` +[Toolset 2.0 migration](TOOLSET.md#migration-from-toolset-10). Підтримка TV входить у контракт: - `with_tvs` мапиться на `withTVs` diff --git a/OPERATIONS.md b/OPERATIONS.md index 7ccad99..a073697 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -4,7 +4,7 @@ This runbook is for operators of eMCP environments. It complements `DOCS.md`/`DOCS.uk.md` with day-2 operational checks. ## 0) Runtime Status Marker -- Target profile: `SPEC 1.0-contract`. +- Target profile: `SPEC 2.0-contract`. - Current runtime baseline: `Gate C baseline implemented`. - Meaning: manager/API transport path and async dispatch endpoints are implemented; production hardening and full integration coverage remain in progress. @@ -217,3 +217,24 @@ Optional live sTask lifecycle proof: - `EMCP_STASK_WORKER_CMD="php artisan stask:worker"` - `EMCP_STASK_WORKER_CWD="/path/to/evo/core"` - optional `EMCP_STASK_POLL_ATTEMPTS` (default: `20`). + +## Toolset 2.0 on a disposable SQLite demo + +The migration from toolset 1.0 is in [TOOLSET.md](TOOLSET.md#migration-from-toolset-10). +Install eMCP and DocumentManager 1.1 or later. To exercise a local pre-release pair, +use Composer path repositories for both checkouts and assign the DocumentManager +checkout version 1.1.0 in the path repository's options.versions. + +For the write and migration regression test, start the demo web process on +loopback with PAT auth and write tools enabled. Issue a local admin PAT with +mcp:read, mcp:call and mcp:write. The test creates fixtures and triggers in the +database. Run it only on a disposable installation: + +```sh +EMCP_LOCAL_MUTATION_TEST=1 \ +EMCP_LOCAL_MCP_URL=http://127.0.0.1:8787/mcp/content \ +EMCP_LOCAL_SQLITE=/absolute/path/to/demo.sqlite \ +EMCP_LOCAL_CORE=/absolute/path/to/demo/core \ +EMCP_LOCAL_ADMIN_TOKEN="$DEMO_PAT" \ +composer run test:integration:toolset-v2 +``` diff --git a/README.md b/README.md index 1d04c3e..2672dbd 100644 --- a/README.md +++ b/README.md @@ -278,8 +278,8 @@ eMCP is the MCP platform layer for the Evo ecosystem: This keeps the core declarative and neutral: one MCP foundation for multiple orchestration concepts. ## Evo Domain Tools -- Implemented now: `evo.content.search|get|root_tree|descendants|ancestors|children|siblings` -- Optional (implemented): `evo.content.neighbors|prev_siblings|next_siblings|children_range|siblings_range` +- Implemented now: `evo.content.search|get|tree|ancestors|siblings` +- [Migration from toolset 1.0](TOOLSET.md#migration-from-toolset-10). - TV-aware queries via structured `with_tvs`, `tv_filters`, `tv_order` - `evo.model.list|get` implemented with per-model explicit allowlist projection and sensitive-field defense-in-depth blacklist diff --git a/README.uk.md b/README.uk.md index f869b26..52070cf 100644 --- a/README.uk.md +++ b/README.uk.md @@ -212,8 +212,8 @@ eMCP є MCP platform layer для екосистеми Evo: Це дає нейтральну декларативну основу: один MCP фундамент для різних orchestration-концепцій. ## Evo Domain Tools -- Реалізовано зараз: `evo.content.search|get|root_tree|descendants|ancestors|children|siblings` -- Опційні (вже реалізовані): `evo.content.neighbors|prev_siblings|next_siblings|children_range|siblings_range` +- Реалізовано зараз: `evo.content.search|get|tree|ancestors|siblings` +- [Перенесення старих викликів](TOOLSET.md#migration-from-toolset-10). - TV-aware запити через структуровані `with_tvs`, `tv_filters`, `tv_order` - `evo.model.list|get` реалізовано з явним per-model allowlist projection і додатковим sensitive blacklist захистом diff --git a/SPEC.md b/SPEC.md index 3889c8d..4312e61 100644 --- a/SPEC.md +++ b/SPEC.md @@ -4,7 +4,7 @@ Цей документ фіксує **обовʼязкові технічні контракти** для реалізації `eMCP`. Status markers: -- `SPEC Version`: `1.0-contract` +- `SPEC Version`: `2.0-contract` - `Runtime Status`: `Gate C baseline validated in demo runtime; RC-1 hardening pending` Normative hierarchy: @@ -16,11 +16,11 @@ Current validation snapshot (2026-03-03): - `make demo-all` PASS (install + smoke + runtime integration). - `php artisan emcp:test` PASS for `initialize` and `tools/list`. - Runtime HTTP integration PASS for `/api/v1/mcp/{server}`. -- Verified content-read tool flow in runtime (`evo.content.search`, `evo.content.root_tree`, `evo.content.get`). +- Verified content-read tool flow in runtime (`evo.content.search`, `evo.content.tree`, `evo.content.get`). - One-click verification writes `demo/logs.md` with request/response evidence, negative transport/security probes (`401/403/413/415/409/429`) and model-safety sanity (`evo.model.get(User)` without sensitive fields). - `demo/logs.md` also captures local `sTask` lifecycle proof (`queued -> completed`) in demo runtime. - CI/local test baseline now includes: `ScopePolicy`/`ServerRegistry` unit checks, async failover behavior checks, SiteContent tree/TV contract checks, security guardrail checks, docs/config/commands consistency checks, upstream adapter smoke checks. -- Optional advanced tree tools (`neighbors`, `prev/next siblings`, `children/siblings range`) are implemented and covered by contract/runtime integration tests. +- Tree and sibling modes are defined in TOOLSET.md for version 2.0. - Streaming policy now enforces proxy/FPM-safe SSE headers (`Content-Type: text/event-stream`, `Cache-Control: no-cache, no-transform`, `X-Accel-Buffering: no`) with dedicated tests. - CI includes migration matrix automation for `sqlite/mysql/pgsql`. - CI/check flow now produces reproducible benchmark and leaderboard artifacts. @@ -535,7 +535,7 @@ Safety: `initialize` response MUST include: - `serverInfo.platform = "eMCP"`. - `serverInfo.platformVersion = `. -- `capabilities.evo.toolsetVersion = "1.0"` (or current toolset version). +- `capabilities.evo.toolsetVersion = "2.0"` (or current toolset version). - This metadata is part of the public contract and required for version-aware ecosystem integrations. - Missing metadata is a breaking contract change. @@ -577,26 +577,15 @@ The project MUST NOT mix styles for the same failure class. `eMCP` MUST ship (or provide canonical stubs for) tool names: - `evo.content.search` - `evo.content.get` -- `evo.content.root_tree` -- `evo.content.descendants` +- `evo.content.tree` - `evo.content.ancestors` -- `evo.content.children` - `evo.content.siblings` Behavior mapping to Evo model API: - `evo.content.search` -> `SiteContent` query + optional `scopeActive|scopePublished|scopeWithoutProtected|scopeWithTVs|scopeTvFilter|scopeTvOrderBy|scopeTagsData|scopeOrderByDate`. -- `evo.content.root_tree` -> `scopeGetRootTree(depth)` + `withTVs(..., ':', true)` + `toTree`. -- `evo.content.descendants` -> `scopeDescendantsOf(id)` (optional depth cap via `where('depth', '<', maxDepth + 1)`). +- `evo.content.tree` uses closure-table descendants for deeper traversal and direct parent selection for one level. - `evo.content.ancestors` -> `scopeAncestorsOf(id)` + default `orderBy('depth', 'desc')`. -- `evo.content.children` -> direct children (`parent = id`) or `getChildren()`. -- `evo.content.siblings` -> `scopeSiblingsOf(id)` and related sibling selectors when requested. - -Advanced optional tools (implemented, non-canonical): -- `evo.content.neighbors` -> `scopeNeighborsOf(id)`. -- `evo.content.prev_siblings` -> `scopePrevSiblingsOf(id)`. -- `evo.content.next_siblings` -> `scopeNextSiblingsOf(id)`. -- `evo.content.children_range` -> `scopeChildrenRangeOf(id, from, to)`. -- `evo.content.siblings_range` -> `scopeSiblingsRangeOf(id, from, to)`. +- `evo.content.siblings` resolves the visible anchor and uses its parent and (menuindex, ID) for selection. ## 10.3 `SiteContent` request/validation contract Input for `evo.content.*` MUST be structured JSON (not raw SQL fragments): @@ -835,7 +824,7 @@ Required keys: - GET returns 405. - `tools/list`, `resources/read`, `tools/call` contracts. - Streaming response headers/content type. -- `evo.content.search/get/root_tree/descendants/ancestors` on real `SiteContent`. +- `evo.content.search/get/tree/ancestors/siblings` on real `SiteContent`. - TV filters/order and default TV fallback (`:d`) on controlled fixtures. - Trace id propagation from request -> response -> audit. - Golden fixtures for canonical tools (`initialize`, `tools/list`, `evo.content.search`, `evo.content.get`) MUST pass in CI. diff --git a/TOOLSET.md b/TOOLSET.md index 9da9fbd..6b27c8e 100644 --- a/TOOLSET.md +++ b/TOOLSET.md @@ -1,11 +1,11 @@ -# TOOLSET — eMCP Canonical Tool Contract v1 +# TOOLSET — eMCP Canonical Tool Contract v2 ## 1. Scope This file defines the public contract for eMCP domain tools. Contract id: - `platform`: `eMCP` -- `toolsetVersion`: `1.0` +- `toolsetVersion`: `2.0` Normative relation: - `SPEC.md` defines platform/runtime rules. @@ -22,33 +22,35 @@ Normative relation: `initialize` response MUST include: - `serverInfo.platform = "eMCP"` - `serverInfo.platformVersion = ""` -- `capabilities.evo.toolsetVersion = "1.0"` +- `capabilities.evo.toolsetVersion = "2.0"` -This platform metadata is part of the public v1 contract. +This platform metadata is part of the public contract. Absence or incompatible change of this metadata is a breaking change (`MAJOR`). -## 4. Canonical Tool Names (v1) +## 4. Canonical Tool Names (v2) ### 4.1 `evo.content.*` - `evo.content.search` - `evo.content.get` -- `evo.content.root_tree` -- `evo.content.descendants` +- `evo.content.tree` - `evo.content.ancestors` -- `evo.content.children` - `evo.content.siblings` -Post-MVP optional: -- `evo.content.neighbors` -- `evo.content.prev_siblings` -- `evo.content.next_siblings` -- `evo.content.children_range` -- `evo.content.siblings_range` - ### 4.2 `evo.model.*` - `evo.model.list` - `evo.model.get` +### 4.3 `evo.elements.*` +- `evo.elements.list` +- `evo.elements.get` + +### 4.4 `evo.write.*` +- `evo.write.content.update` +- `evo.write.content.create` +- `evo.write.content.publish` +- `evo.write.elements.save` +- `evo.write.cache.clear` + ## 5. Common Tool Call Envelope MCP `tools/call` payload: @@ -95,20 +97,19 @@ Arguments: - `id` int required - `with_tvs` string[] optional -### 6.3 `evo.content.root_tree` -Arguments: -- `depth` int optional -- `with_tvs` string[] optional -- `limit` int required -- `offset` int optional +### 6.3 `evo.content.tree` +- `id` required, with 0 representing the virtual site root. +- `depth` defaults to 1. The configured depth cap allows one extra level from the virtual root. +- `menuindex_from` and `menuindex_to` are optional inclusive bounds available at depth 1. +- `with_tvs`, required `limit` and optional `offset` apply to a flat list sorted by parent, menuindex and ID. -### 6.4 `evo.content.descendants|ancestors|children|siblings` -Arguments: -- `id` int required -- `depth` int optional (where relevant) -- `with_tvs` string[] optional -- `limit` int required -- `offset` int optional +### 6.4 `evo.content.siblings` and `evo.content.ancestors` +- Siblings requires a positive `id`; `direction` is `all` (default), `before`, `after` or `adjacent`. +- Before and after are nearest first by the total order (menuindex, ID); adjacent returns at most the nearest visible record on each side, previous first. +- Only all accepts inclusive `menuindex_from` and `menuindex_to`. All, before and after require `limit` and accept `offset`; adjacent accepts neither. +- Ancestors requires a positive `id` and accepts optional `depth`. Omit depth for the complete visible path up to the server result limit. The result is ordered farthest to nearest. A server-limited path keeps the nearest ancestors and sets `meta.truncated`. +- All five content tools accept `with_tvs` as a list of TV names. Use the suffix `:d` to request the default when no value is stored. +- A missing, trashed or inaccessible anchor gives an empty list for tree, siblings and ancestors. ### 6.5 `evo.model.list` Arguments: @@ -130,6 +131,12 @@ Arguments: - `model` string required (must be in allowlist) - `id` int required +### 6.7 Elements and write tools +Element reads use the edit permission for the selected type. List returns names and metadata; get also returns the code field and honors ID before exact name. +Element saves use the corresponding new or save permission and the server's code-write policy. + +Document update requires save_document. An actual change to published, pub_date or unpub_date also requires publish_document. Dates are non-negative integer timestamps; zero clears a date. Rejected publication changes and failures within the edit transaction leave both document fields and TVs unchanged. TV names must belong to the destination template. The result reports requested field and TV names whose stored values changed. + ## 7. Response Contract Tool responses SHOULD return: - `items` array for list-like tools @@ -145,7 +152,7 @@ Example: "limit": 20, "offset": 0, "count": 0, - "toolsetVersion": "1.0" + "toolsetVersion": "2.0" } } ``` @@ -174,3 +181,27 @@ Canonical mapping: - large responses MUST be paginated - `limit` cannot exceed configured `max_result_items` - serialized result cannot exceed configured `max_result_bytes` + +## Migration from toolset 1.0 + +Deploy both packages together. Toolset 2.0 requires DocumentManager 1.1.0 for atomic document and TV updates. +The names below are relative to the `evo.content.` prefix. + +| v1 call | v2 call | +| --- | --- | +| `root_tree(depth=d)` | `tree(id=0, depth=d+1)`; use depth 2 for the old default. | +| `children(id)` | `tree(id, depth=1)` | +| `descendants(id, depth=d)` | `tree(id, depth=d)`; use depth 1 for omitted or null depth. | +| `children_range(id, from, to)` | `tree(id, depth=1, menuindex_from=from, menuindex_to=to)` | +| `siblings(id)` | `siblings(id, direction=all)` | +| `prev_siblings(id)` | `siblings(id, direction=before)` | +| `next_siblings(id)` | `siblings(id, direction=after)` | +| `neighbors(id)` | `siblings(id, direction=adjacent)`; omit limit and offset. | +| `siblings_range(id, from, to)` | `siblings(id, direction=all, menuindex_from=from, menuindex_to=to)` | +| `ancestors(id, depth, limit, offset)` | `ancestors(id, depth)`; slice client-side if needed and honor meta.truncated. | +| `search(...)`, `get(...)` | Same names and arguments, now with the supported TV and search options in the schema. | + +- Carry over `with_tvs` and `limit`/`offset` where supported. Restart root-tree paging at offset 0 because v1 sorted only by ID. +- Sibling directions compare `(menuindex, id)`. Equal menu positions are ordered by ID. Adjacent finds the closest accessible record on either side even across position gaps; v1 neighbors used exact positions ±1. Restart paging when equal positions could change the result set. +- Model, element and write names are unchanged. For document updates, a forbidden publication change now rejects the whole request, and the returned change lists describe persisted changes. Send TVs by name on the target template. +- Refresh the client’s tool discovery after switching versions. A client that still needs the v1 semantics should finish its migration against the v1 release before the server is upgraded. diff --git a/composer.json b/composer.json index dad9c74..f4d266a 100644 --- a/composer.json +++ b/composer.json @@ -13,6 +13,7 @@ "require": { "php": "^8.3", "evolution-cms/evolution": "^3.5.2", + "evolutioncms-services/document-manager": "^1.1", "laravel/mcp": "^0.5.9", "seiger/sapi": "^1.0", "seiger/stask": "^1.0.10 || ^2.0" @@ -38,6 +39,7 @@ "test:unit:model-field-leakage": "php tests/Unit/ModelFieldPolicyLeakageTest.php", "test:unit:model-field-schema": "php tests/Unit/ModelFieldPolicySchemaTest.php", "test:unit:settings-file": "php tests/Unit/SettingsFileTest.php", + "test:unit:tool-definitions": "php tests/Unit/ToolDefinitionsTest.php", "test:unit:tool-registry": "php tests/Unit/ToolRegistryTest.php", "test:unit:tool-error": "php tests/Unit/ToolErrorTest.php", "test:unit:governance-lock": "php tests/Unit/GovernanceLockWriteTest.php", @@ -47,6 +49,7 @@ "test:feature:streaming-limits": "php tests/Feature/StreamingAndResultLimitsBehaviorTest.php", "test:feature:call-permissions-route": "php tests/Feature/CallPermissionsRouteTest.php", "test:integration:transport": "php tests/Integration/TransportEndpointsHttpTest.php", + "test:integration:toolset-v2": "php tests/Integration/ToolsetV2SqliteHttpTest.php", "test:integration:closure": "php tests/Integration/ClosureTableInvariantsHttpTest.php", "test:integration:migrations": "php tests/Integration/MigrationCycleRuntimeTest.php", "test:integration:runtime": "php tests/Integration/RuntimeIntegrationHttpTest.php", @@ -86,6 +89,7 @@ "@test:unit:model-field-schema", "@test:unit:settings-file", "@test:unit:tool-registry", + "@test:unit:tool-definitions", "@test:unit:tool-error", "@test:unit:governance-lock", "@test:phase25", @@ -110,6 +114,7 @@ "@test:integration:migrations", "@test:integration:transport", "@test:integration:closure", + "@test:integration:toolset-v2", "@test:integration:runtime" ] }, diff --git a/config/eMCPSettings.php b/config/eMCPSettings.php index 8348187..c57a903 100644 --- a/config/eMCPSettings.php +++ b/config/eMCPSettings.php @@ -2,7 +2,6 @@ return [ 'enable' => true, - 'toolset_version' => '1.0', 'mode' => [ 'internal' => true, diff --git a/scripts/demo_verify.sh b/scripts/demo_verify.sh index 0ff27a6..8b25ce6 100644 --- a/scripts/demo_verify.sh +++ b/scripts/demo_verify.sh @@ -200,11 +200,11 @@ session_id="" initialize_payload='{"jsonrpc":"2.0","id":"init-doc","method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"emcp-demo-verify","version":"1.0.0"}}}' tools_list_payload='{"jsonrpc":"2.0","id":"tools-doc","method":"tools/list","params":{}}' content_search_payload='{"jsonrpc":"2.0","id":"search-doc","method":"tools/call","params":{"name":"evo.content.search","arguments":{"limit":3,"offset":0}}}' -content_root_tree_payload='{"jsonrpc":"2.0","id":"root-doc","method":"tools/call","params":{"name":"evo.content.root_tree","arguments":{"limit":3,"offset":0,"depth":2}}}' +content_root_tree_payload='{"jsonrpc":"2.0","id":"root-doc","method":"tools/call","params":{"name":"evo.content.tree","arguments":{"id":0,"limit":3,"offset":0,"depth":3}}}' content_get_payload='{"jsonrpc":"2.0","id":"get-doc","method":"tools/call","params":{"name":"evo.content.get","arguments":{"id":1}}}' -content_neighbors_payload='{"jsonrpc":"2.0","id":"neighbors-doc","method":"tools/call","params":{"name":"evo.content.neighbors","arguments":{"id":1,"limit":3,"offset":0}}}' -content_children_range_payload='{"jsonrpc":"2.0","id":"children-range-doc","method":"tools/call","params":{"name":"evo.content.children_range","arguments":{"id":1,"from":0,"to":5,"limit":3,"offset":0}}}' -content_children_range_invalid_payload='{"jsonrpc":"2.0","id":"children-range-invalid-doc","method":"tools/call","params":{"name":"evo.content.children_range","arguments":{"id":1,"from":5,"to":2,"limit":1,"offset":0}}}' +content_neighbors_payload='{"jsonrpc":"2.0","id":"neighbors-doc","method":"tools/call","params":{"name":"evo.content.siblings","arguments":{"id":1,"direction":"adjacent"}}}' +content_children_range_payload='{"jsonrpc":"2.0","id":"children-range-doc","method":"tools/call","params":{"name":"evo.content.tree","arguments":{"id":1,"menuindex_from":0,"menuindex_to":5,"limit":3,"offset":0}}}' +content_children_range_invalid_payload='{"jsonrpc":"2.0","id":"children-range-invalid-doc","method":"tools/call","params":{"name":"evo.content.tree","arguments":{"id":1,"menuindex_from":5,"menuindex_to":2,"limit":1,"offset":0}}}' init_headers_file="${TMP_DIR}/init.headers" init_raw=$(curl -sS -D "${init_headers_file}" \ @@ -676,7 +676,7 @@ Response: ${search_response} \`\`\` -### 4) site content via evo.content.root_tree +### 4) site content via evo.content.tree Request: \`\`\`json @@ -708,7 +708,7 @@ Contract note: - \`result.structuredContent\` is the canonical contract payload. - \`result.content[].text\` is a compatibility mirror for MCP clients that rely on text blocks. -### 6) optional tool probe: evo.content.neighbors +### 6) optional tool probe: evo.content.siblings Request: \`\`\`json @@ -722,7 +722,7 @@ Response: ${neighbors_response} \`\`\` -### 7) optional tool probe: evo.content.children_range +### 7) optional tool probe: evo.content.tree Request: \`\`\`json @@ -736,7 +736,7 @@ Response: ${children_range_response} \`\`\` -### 8) optional tool negative probe: evo.content.children_range (from > to) +### 8) optional tool negative probe: evo.content.tree (from > to) Request: \`\`\`json diff --git a/scripts/governance_helpers.php b/scripts/governance_helpers.php index fbda5d7..60b352e 100644 --- a/scripts/governance_helpers.php +++ b/scripts/governance_helpers.php @@ -39,6 +39,11 @@ function governance_parse_toolset(string $toolsetPath): array continue; } + if (str_starts_with($trimmed, '### 4.3') || str_starts_with($trimmed, '### 4.4')) { + $mode = 'additional'; + continue; + } + if ($mode !== '' && str_starts_with($trimmed, '## 5.')) { break; } diff --git a/skills/evolution-cms-mcp/SKILL.md b/skills/evolution-cms-mcp/SKILL.md index 659d2c3..4f17efb 100644 --- a/skills/evolution-cms-mcp/SKILL.md +++ b/skills/evolution-cms-mcp/SKILL.md @@ -12,7 +12,7 @@ metadata: - cms - content-management package: evolution-cms/emcp - toolset-version: "1.0" + toolset-version: "2.0" --- # Evolution CMS via eMCP @@ -73,8 +73,8 @@ administration (install, deploy, database backups). Never guess ids, TV names or element names. 2. **Always paginate.** Content and model list tools require `limit` (max 100 by default) and accept `offset`. Page until `meta.count < limit`. -3. **Prefer the narrowest tool.** `children` over `descendants`, `search` with - `parent` + `depth` over `root_tree`, `evo.elements.list` (no code) before +3. **Prefer the narrowest tool.** `tree` with `depth: 1` for children, `search` with + `parent` and `depth` for filtered results, `evo.elements.list` (no code) before `evo.elements.get` (with code). 4. **Confirm before changes the user cannot undo.** `evo.write.content.update` and `evo.write.elements.save` overwrite without a revision. Show the diff of @@ -90,10 +90,10 @@ administration (install, deploy, database backups). | Task | Tools | |---|---| -| Site structure | `evo.content.root_tree`, `children`, `descendants`, `ancestors`, `siblings` | +| Site structure | `evo.content.tree`, `evo.content.ancestors`, `evo.content.siblings` | | Find documents | `evo.content.search` (filters, TV filters, TV order, tags) | | Read one document with body | `evo.content.get` (`with_tvs`) | -| Ordering by menu position | `evo.content.neighbors`, `prev_siblings`, `next_siblings`, `children_range`, `siblings_range` | +| Ordering by menu position | `evo.content.siblings` directions and `evo.content.tree` ranges | | Write documents | `evo.write.content.create`, `evo.write.content.update`, `evo.write.content.publish` | | Templates, TVs, chunks, snippets, plugins | `evo.elements.list`, `evo.elements.get`, `evo.write.elements.save` | | Users, roles, permissions, categories | `evo.model.list`, `evo.model.get` | diff --git a/skills/evolution-cms-mcp/references/core-tools.md b/skills/evolution-cms-mcp/references/core-tools.md index f9831b4..8fef957 100644 --- a/skills/evolution-cms-mcp/references/core-tools.md +++ b/skills/evolution-cms-mcp/references/core-tools.md @@ -1,6 +1,6 @@ # eMCP core tools -Canonical contract: `TOOLSET.md` in the eMCP package (toolset version 1.0). +Canonical contract: `TOOLSET.md` in the eMCP package (toolset version 2.0). All tools are called with MCP `tools/call`: `{"name": "", "arguments": {...}}`. ## Contents @@ -20,15 +20,9 @@ All return non-deleted documents the acting user may see (document groups apply) | Tool | Required | Optional | |---|---|---| | `evo.content.get` | `id` | `with_tvs` | -| `evo.content.root_tree` | `limit` | `depth`, `offset`, `with_tvs` | -| `evo.content.children` | `id`, `limit` | `offset`, `with_tvs` | -| `evo.content.descendants` | `id`, `limit` | `depth`, `offset`, `with_tvs` | -| `evo.content.ancestors` | `id`, `limit` | `depth`, `offset`, `with_tvs` | -| `evo.content.siblings` | `id`, `limit` | `offset`, `with_tvs` | -| `evo.content.neighbors` | `id`, `limit` | `offset`, `with_tvs` | -| `evo.content.prev_siblings` / `next_siblings` | `id`, `limit` | `offset`, `with_tvs` | -| `evo.content.children_range` | `id`, `from`, `limit` | `to`, `offset`, `with_tvs` | -| `evo.content.siblings_range` | `id`, `from`, `limit` | `to`, `offset`, `with_tvs` | +| `evo.content.tree` | `id`, `limit` | `depth`, `offset`, `with_tvs`, `menuindex_from`, `menuindex_to` | +| `evo.content.ancestors` | `id` | `depth`, `with_tvs` | +| `evo.content.siblings` | `id`, `limit` (except `adjacent`) | `direction`, `offset`, `with_tvs`, `menuindex_from`, `menuindex_to` | | `evo.content.search` | `limit` | see below | List items carry `id, parent, pagetitle, longtitle, description, alias, published, deleted, @@ -39,7 +33,7 @@ cacheable, richtext, contentType, editedby, createdby, publishedon`. `with_tvs`: TV names, `"price"` for the stored value or `"price:d"` to fall back to the TV default when a document has no value. -Ranges (`children_range`, `siblings_range`) select by `menuindex` from `from` to `to`. +Ranges use inclusive `menuindex_from` and `menuindex_to` on `tree` at depth 1 or `siblings` in the `all` direction. ## Search filters @@ -109,7 +103,7 @@ Code field per type: `content` (template), `default_text` (tv), `snippet` (chunk ## Responses ```json -{"items": [], "meta": {"limit": 20, "offset": 0, "count": 0, "toolsetVersion": "1.0"}} +{"items": [], "meta": {"limit": 20, "offset": 0, "count": 0, "toolsetVersion": "2.0"}} ``` Get-like tools return `item` (null when not found or not visible). diff --git a/skills/evolution-cms-mcp/references/workflows.md b/skills/evolution-cms-mcp/references/workflows.md index 5a433c5..9030a23 100644 --- a/skills/evolution-cms-mcp/references/workflows.md +++ b/skills/evolution-cms-mcp/references/workflows.md @@ -16,10 +16,10 @@ Prerequisites are open for any write step. Recipes for `aimage.*`, `amount.*` an ## Map an unknown site -1. `evo.content.root_tree` `{"depth": 2, "limit": 100}`. +1. `evo.content.tree` `{"id": 0, "depth": 3, "limit": 100}`. 2. `evo.elements.list` `{"type": "template"}` and `{"type": "tv"}` to learn which templates and TVs exist; note TV names for later `with_tvs`. -3. For a section, `evo.content.children` `{"id":
, "limit": 100}`. +3. For a section, `evo.content.tree` `{"id":
, "depth": 1, "limit": 100}`. 4. Summarise the tree (ids, titles, templates) before proposing any change. ## SEO audit of a section @@ -43,10 +43,10 @@ findings and recorded fixes, including missing-page drafts, background checks an ## Restructure the menu -1. `evo.content.children` for the parent to get current `menuindex` values. +1. `evo.content.tree` for the parent to get current `menuindex` values. 2. Propose the new order; on approval update `fields.menuindex` (and `fields.parent` to move a document; `parent` 0 is the root). -3. Verify with `evo.content.children` again. +3. Verify with `evo.content.tree` again. ## Fix a template or chunk diff --git a/src/Console/Commands/eMcpTestCommand.php b/src/Console/Commands/eMcpTestCommand.php index 859e715..dfb2d97 100644 --- a/src/Console/Commands/eMcpTestCommand.php +++ b/src/Console/Commands/eMcpTestCommand.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Console\Commands; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Http\Controllers\McpManagerController; use EvolutionCMS\eMCP\Servers\ContentServer; use EvolutionCMS\eMCP\Services\ServerRegistry; @@ -245,13 +247,18 @@ private function requiredToolsForServer(string $serverClass, array $expected = [ return array_values(array_unique(array_merge([ 'evo.content.search', 'evo.content.get', - 'evo.content.root_tree', - 'evo.content.descendants', + 'evo.content.tree', 'evo.content.ancestors', - 'evo.content.children', 'evo.content.siblings', 'evo.model.list', 'evo.model.get', + 'evo.elements.list', + 'evo.elements.get', + 'evo.write.content.update', + 'evo.write.content.create', + 'evo.write.content.publish', + 'evo.write.elements.save', + 'evo.write.cache.clear', ], $extra))); } @@ -355,7 +362,7 @@ private function validateInitializeMetadata(array $initializeJson): bool return false; } - $expectedToolsetVersion = (string)config('cms.settings.eMCP.toolset_version', '1.0'); + $expectedToolsetVersion = ToolContract::VERSION; if ($toolsetVersion !== $expectedToolsetVersion) { $this->error( 'initialize metadata missing/invalid capabilities.evo.toolsetVersion. ' . diff --git a/src/Contracts/ToolArguments/ContentNodeListArgs.php b/src/Contracts/ToolArguments/ContentNodeListArgs.php deleted file mode 100644 index 39fef30..0000000 --- a/src/Contracts/ToolArguments/ContentNodeListArgs.php +++ /dev/null @@ -1,21 +0,0 @@ - $withTvEntries - * @param array $withTvNames - */ - public function __construct( - public int $id, - public PagingArgs $paging, - public array $withTvEntries, - public array $withTvNames, - public ?int $depth = null - ) { - } -} diff --git a/src/Contracts/ToolArguments/ContentNodeRangeArgs.php b/src/Contracts/ToolArguments/ContentNodeRangeArgs.php deleted file mode 100644 index b84f99c..0000000 --- a/src/Contracts/ToolArguments/ContentNodeRangeArgs.php +++ /dev/null @@ -1,22 +0,0 @@ - $withTvEntries - * @param array $withTvNames - */ - public function __construct( - public int $id, - public int $from, - public ?int $to, - public PagingArgs $paging, - public array $withTvEntries, - public array $withTvNames - ) { - } -} diff --git a/src/Contracts/ToolArguments/ContentRootTreeArgs.php b/src/Contracts/ToolArguments/ContentRootTreeArgs.php deleted file mode 100644 index abfd929..0000000 --- a/src/Contracts/ToolArguments/ContentRootTreeArgs.php +++ /dev/null @@ -1,20 +0,0 @@ - $withTvEntries - * @param array $withTvNames - */ - public function __construct( - public int $depth, - public PagingArgs $paging, - public array $withTvEntries, - public array $withTvNames - ) { - } -} diff --git a/src/Contracts/ToolResponses/ListToolResponse.php b/src/Contracts/ToolResponses/ListToolResponse.php index e6dd3b8..c89144a 100644 --- a/src/Contracts/ToolResponses/ListToolResponse.php +++ b/src/Contracts/ToolResponses/ListToolResponse.php @@ -4,10 +4,14 @@ namespace EvolutionCMS\eMCP\Contracts\ToolResponses; +/** Structured MCP list response shared by paged queries and bounded paths. */ final readonly class ListToolResponse { /** + * Carry the visible records and applied bounds for this result. + * * @param array> $items + * @param bool|null $truncated Whether a bounded path was shortened, or null for paged lists. */ public function __construct( public array $items, @@ -15,7 +19,8 @@ public function __construct( public int $offset, public int $count, public string $toolsetVersion, - public ?string $model = null + public ?string $model = null, + public ?bool $truncated = null, ) { } @@ -35,6 +40,10 @@ public function toArray(): array $meta['model'] = $this->model; } + if ($this->truncated !== null) { + $meta['truncated'] = $this->truncated; + } + return [ 'items' => $this->items, 'meta' => $meta, diff --git a/src/Http/Controllers/McpManagerController.php b/src/Http/Controllers/McpManagerController.php index d082ad5..a7dea64 100644 --- a/src/Http/Controllers/McpManagerController.php +++ b/src/Http/Controllers/McpManagerController.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Http\Controllers; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Services\AuditLogger; use EvolutionCMS\eMCP\Services\SecurityPolicy; use EvolutionCMS\eMCP\Services\ServerRegistry; @@ -228,7 +230,7 @@ private function injectPlatformMetadata(Response $response): void $payload['result']['serverInfo']['platform'] = 'eMCP'; $payload['result']['serverInfo']['platformVersion'] = $this->packageVersion(); - $payload['result']['capabilities']['evo']['toolsetVersion'] = (string)config('cms.settings.eMCP.toolset_version', '1.0'); + $payload['result']['capabilities']['evo']['toolsetVersion'] = ToolContract::VERSION; // Which site this is and which domains the installation serves, so an agent told "put // it on site.com" can check rather than guess (one installation may serve several). $payload['result']['serverInfo']['site'] = \EvolutionCMS\eMCP\Support\SiteDomains::describe( diff --git a/src/Servers/ContentServer.php b/src/Servers/ContentServer.php index dda9e91..b9c5f29 100644 --- a/src/Servers/ContentServer.php +++ b/src/Servers/ContentServer.php @@ -4,18 +4,11 @@ namespace EvolutionCMS\eMCP\Servers; -use EvolutionCMS\eMCP\Tools\Content\ContentChildrenTool; -use EvolutionCMS\eMCP\Tools\Content\ContentChildrenRangeTool; use EvolutionCMS\eMCP\Tools\Content\ContentGetTool; -use EvolutionCMS\eMCP\Tools\Content\ContentRootTreeTool; +use EvolutionCMS\eMCP\Tools\Content\ContentTreeTool; use EvolutionCMS\eMCP\Tools\Content\ContentSearchTool; -use EvolutionCMS\eMCP\Tools\Content\ContentDescendantsTool; use EvolutionCMS\eMCP\Tools\Content\ContentAncestorsTool; -use EvolutionCMS\eMCP\Tools\Content\ContentNeighborsTool; -use EvolutionCMS\eMCP\Tools\Content\ContentNextSiblingsTool; -use EvolutionCMS\eMCP\Tools\Content\ContentPrevSiblingsTool; use EvolutionCMS\eMCP\Tools\Content\ContentSiblingsTool; -use EvolutionCMS\eMCP\Tools\Content\ContentSiblingsRangeTool; use EvolutionCMS\eMCP\Tools\Elements\ElementsGetTool; use EvolutionCMS\eMCP\Tools\Elements\ElementsListTool; use EvolutionCMS\eMCP\Tools\ModelCatalog\ModelGetTool; @@ -34,23 +27,17 @@ use Laravel\Mcp\Server\Attributes\Version; #[Name('eMCP Content Server')] -#[Version('1.0.0')] +#[Version('2.0.0')] #[Instructions('Evolution CMS content and elements. Every call runs as the token owner with their manager permissions; evo.write.* tools change the site and need the mcp:write scope.')] +/** Expose the current Evo toolset together with extra tools registered on the content server. */ class ContentServer extends Server { protected array $tools = [ ContentSearchTool::class, ContentGetTool::class, - ContentRootTreeTool::class, - ContentDescendantsTool::class, + ContentTreeTool::class, ContentAncestorsTool::class, - ContentChildrenTool::class, ContentSiblingsTool::class, - ContentNeighborsTool::class, - ContentPrevSiblingsTool::class, - ContentNextSiblingsTool::class, - ContentChildrenRangeTool::class, - ContentSiblingsRangeTool::class, ModelListTool::class, ModelGetTool::class, ElementsListTool::class, diff --git a/src/Support/ToolContract.php b/src/Support/ToolContract.php new file mode 100644 index 0000000..86fd8f8 --- /dev/null +++ b/src/Support/ToolContract.php @@ -0,0 +1,57 @@ + $extraMeta + * @return array + * @since 0.3.0 + */ + public static function listing(JsonSchema $schema, array $extraMeta = []): array + { + return [ + 'items' => $schema->array()->items($schema->object())->required() + ->description('Returned records in the order defined by the tool. Empty when there are no matches.'), + 'meta' => $schema->object([ + 'limit' => $schema->integer()->min(1)->required()->description('Result limit applied by the tool.'), + 'offset' => $schema->integer()->min(0)->required()->description('Number of matching records skipped.'), + 'count' => $schema->integer()->min(0)->required()->description('Number of returned records in this response.'), + 'toolsetVersion' => $schema->string()->enum([self::VERSION])->required()->description('Version of the Evo tool contract.'), + ] + $extraMeta)->required()->withoutAdditionalProperties(), + ]; + } + + /** + * Describe a single record or a successful write receipt. + * + * @param array $fields + * @param array $extraMeta + * @return array + * @since 0.3.0 + */ + public static function item(JsonSchema $schema, array $fields = [], array $extraMeta = [], bool $nullable = true): array + { + return [ + 'item' => $schema->object($fields)->required()->nullable($nullable) + ->description($nullable ? 'The matching record, or null when it was not found.' : 'The successful write result.'), + 'meta' => $schema->object([ + 'toolsetVersion' => $schema->string()->enum([self::VERSION])->required()->description('Version of the Evo tool contract.'), + ] + $extraMeta)->required()->withoutAdditionalProperties(), + ]; + } +} diff --git a/src/Tools/Content/BaseContentTool.php b/src/Tools/Content/BaseContentTool.php index d10037d..baa6636 100644 --- a/src/Tools/Content/BaseContentTool.php +++ b/src/Tools/Content/BaseContentTool.php @@ -4,17 +4,23 @@ namespace EvolutionCMS\eMCP\Tools\Content; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Contracts\ToolResponses\ItemToolResponse; use EvolutionCMS\eMCP\Contracts\ToolResponses\ListToolResponse; use EvolutionCMS\eMCP\Mappers\SiteContentMapper; use EvolutionCMS\Models\SiteContent; +use Illuminate\Contracts\JsonSchema\JsonSchema; use Illuminate\Database\Eloquent\Builder; +use Illuminate\JsonSchema\Types\ArrayType; +use Illuminate\JsonSchema\Types\Type; use Illuminate\Validation\ValidationException; use Laravel\Mcp\Response; use Laravel\Mcp\Request; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Tool; +/** Shared validation, visibility and structured results for document tools. */ abstract class BaseContentTool extends Tool { private ?SiteContentMapper $siteContentMapper = null; @@ -171,6 +177,90 @@ protected function applyManagerAccess(Builder $query, string $table = 'site_cont } } + /** + * Fetch a visible, live document to anchor tree or sibling traversal. + * + * @since 0.3.0 + */ + protected function findAnchor(int $id): ?SiteContent + { + $query = SiteContent::query()->select('site_content.id', 'site_content.parent', 'site_content.menuindex') + ->where('site_content.id', $id) + ->where('site_content.deleted', 0); + $this->applyManagerAccess($query); + + return $query->first(); + } + + /** + * Advertise the TV projection accepted by every content reader. + * + * @since 0.3.0 + */ + protected function tvSchema(JsonSchema $schema): ArrayType + { + return $schema->array()->items($schema->string())->nullable() + ->description('TV names to return under tvs. Append :d to a name to fall back to its default value.'); + } + + /** + * Advertise the paging arguments applied after scope, filters and sorting. + * + * @return array + * @since 0.3.0 + */ + protected function pagingSchema(JsonSchema $schema, bool $required = true): array + { + $limit = $schema->integer()->min(1)->description('Maximum items to return, up to the configured server limit.'); + if ($required) { + $limit->required(); + } + + return [ + 'limit' => $limit, + 'offset' => $schema->integer()->min(0)->nullable()->default(0) + ->description('Number of matching records to skip after sorting.'), + ]; + } + + /** + * Check inclusive menuindex bounds before building a query. + * + * @since 0.3.0 + */ + protected function validateMenuindexRange(?int $from, ?int $to): void + { + if ($from !== null && $to !== null && $from > $to) { + throw ValidationException::withMessages(['menuindex_to' => 'Must be greater than or equal to menuindex_from.']); + } + } + + /** + * Apply an optional inclusive range on the named resource table. + * + * @since 0.3.0 + */ + protected function applyMenuindexRange(Builder $query, string $table, ?int $from, ?int $to): void + { + if ($from !== null) { + $query->where($table . '.menuindex', '>=', $from); + } + if ($to !== null) { + $query->where($table . '.menuindex', '<=', $to); + } + } + + /** + * Advertise the paginated response shared by document listings. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::listing($schema); + } + protected function resolveMaxLimit(): int { $limitA = max(1, (int)config('cms.settings.eMCP.limits.max_result_items', 100)); @@ -432,9 +522,11 @@ protected function projectItem(SiteContent $row, array $tvNames = []): array } /** + * Return a document page or an ancestor path with its truncation indicator. + * * @param array> $items */ - protected function respondList(array $items, int $limit, int $offset): ResponseFactory + protected function respondList(array $items, int $limit, int $offset, ?bool $truncated = null): ResponseFactory { return Response::structured( (new ListToolResponse( @@ -442,7 +534,8 @@ protected function respondList(array $items, int $limit, int $offset): ResponseF $limit, $offset, count($items), - (string)config('cms.settings.eMCP.toolset_version', '1.0') + ToolContract::VERSION, + truncated: $truncated, ))->toArray() ); } @@ -455,7 +548,7 @@ protected function respondItem(?array $item): ResponseFactory return Response::structured( (new ItemToolResponse( $item, - (string)config('cms.settings.eMCP.toolset_version', '1.0') + ToolContract::VERSION ))->toArray() ); } diff --git a/src/Tools/Content/ContentAncestorsTool.php b/src/Tools/Content/ContentAncestorsTool.php index ecb05e2..9aed9b0 100644 --- a/src/Tools/Content/ContentAncestorsTool.php +++ b/src/Tools/Content/ContentAncestorsTool.php @@ -4,22 +4,22 @@ namespace EvolutionCMS\eMCP\Tools\Content; -use EvolutionCMS\eMCP\Contracts\ToolArguments\ContentNodeListArgs; -use EvolutionCMS\eMCP\Contracts\ToolArguments\PagingArgs; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\Models\SiteContent; use Illuminate\Contracts\JsonSchema\JsonSchema; +use Illuminate\Validation\ValidationException; use Laravel\Mcp\Request; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Attributes\Description; use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.content.ancestors')] -#[Description('Read ancestors of a content node with optional depth cap and pagination.')] +#[Description('Read a visible document’s ancestor path, farthest to nearest and excluding the anchor. A server limit keeps the closest ancestors and sets meta.truncated. Use evo.content.tree to walk down instead.')] +/** Read a bounded ancestor path suitable for breadcrumbs. */ class ContentAncestorsTool extends BaseContentTool { - /** - * @return array - */ + /** Normalize the anchor ID, optional depth and requested TV names. */ protected function validateStage(Request $request): array { $validated = $request->validate([ @@ -27,89 +27,83 @@ protected function validateStage(Request $request): array 'depth' => ['nullable', 'integer', 'min:1'], 'with_tvs' => ['nullable', 'array'], 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], - 'offset' => ['nullable', 'integer', 'min:0'], ]); - [$limit, $offset] = $this->resolveLimitOffset($validated); - $depth = isset($validated['depth']) ? $this->resolveDepth((int)$validated['depth']) : null; - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); + if ($request->get('limit') !== null || $request->get('offset') !== null) { + throw ValidationException::withMessages(['limit' => 'Ancestors returns a bounded path; omit limit and offset.']); + } return [ - 'args' => new ContentNodeListArgs( - (int)$validated['id'], - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'], - $depth - ), + 'id' => (int)$validated['id'], + 'depth' => isset($validated['depth']) ? $this->resolveDepth((int)$validated['depth']) : null, + 'limit' => $this->resolveMaxLimit(), + 'tvs' => $this->normalizeWithTvs($validated['with_tvs'] ?? null), ]; } - protected function queryStage(array $validated): mixed + /** Retrieve the nearest visible ancestors, fetching one extra to detect truncation. */ + protected function queryStage(array $validated): array { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; + if ($this->findAnchor($validated['id']) === null) { + return []; + } - $query = SiteContent::query() - ->select('site_content.*') - ->ancestorsOf($args->id) + $query = SiteContent::query()->select('site_content.*') + ->ancestorsOf($validated['id']) ->where('site_content.deleted', 0) - ->orderBy('site_content_closure.depth', 'desc') - ->orderBy('site_content.id', 'asc'); + ->orderBy('site_content_closure.depth') + ->orderBy('site_content.id', 'desc'); - if ($args->depth !== null) { - $query->where('site_content_closure.depth', '<=', $args->depth); + if ($validated['depth'] !== null) { + $query->where('site_content_closure.depth', '<=', $validated['depth']); } - $this->applyManagerAccess($query); - - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries); + if ($validated['tvs']['entries'] !== []) { + $query->withTVs($validated['tvs']['entries']); } - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); + return $query->limit($validated['limit'] + 1)->get()->all(); } - /** - * @return array - */ + /** Keep the nearest ancestors within the limit and return them in root-to-parent order. */ protected function mapStage(mixed $queryResult, array $validated): array { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; + $limit = $validated['limit']; return [ - 'items' => $this->projectItems($queryResult, $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, + 'items' => $this->projectItems(array_reverse(array_slice($queryResult, 0, $limit)), $validated['tvs']['names']), + 'truncated' => count($queryResult) > $limit, ]; } + /** Mark whether the server limit shortened the path requested by the caller. */ protected function respondStage(array $mapped, array $validated): ResponseFactory { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); + return $this->respondList($mapped['items'], $validated['limit'], 0, $mapped['truncated']); } - /** - * @return array - */ + /** Advertise only the anchor ID, optional depth and TV projection. */ public function schema(JsonSchema $schema): array { return [ - 'id' => $schema->integer()->min(1)->required(), - 'depth' => $schema->integer()->min(1)->nullable(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), + 'id' => $schema->integer()->min(1)->required()->description('ID of the visible document whose ancestor path to read.'), + 'depth' => $schema->integer()->min(1)->nullable() + ->description('Maximum distance from the document in levels. Omit for a path up to the server result limit.'), + 'with_tvs' => $this->tvSchema($schema), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::listing($schema, [ + 'truncated' => $schema->boolean()->required() + ->description('Whether the server result limit shortened the visible ancestor path.'), + ]); + } } diff --git a/src/Tools/Content/ContentChildrenRangeTool.php b/src/Tools/Content/ContentChildrenRangeTool.php deleted file mode 100644 index 113c1d2..0000000 --- a/src/Tools/Content/ContentChildrenRangeTool.php +++ /dev/null @@ -1,122 +0,0 @@ - - */ - protected function validateStage(Request $request): array - { - $validated = $request->validate([ - 'id' => ['required', 'integer', 'min:1'], - 'from' => ['required', 'integer', 'min:0'], - 'to' => ['nullable', 'integer', 'min:0'], - 'with_tvs' => ['nullable', 'array'], - 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], - 'offset' => ['nullable', 'integer', 'min:0'], - ]); - - $from = (int)$validated['from']; - $to = isset($validated['to']) ? (int)$validated['to'] : null; - if ($to !== null && $to < $from) { - throw ValidationException::withMessages([ - 'to' => 'to must be greater than or equal to from.', - ]); - } - - [$limit, $offset] = $this->resolveLimitOffset($validated); - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); - - return [ - 'args' => new ContentNodeRangeArgs( - (int)$validated['id'], - $from, - $to, - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'] - ), - ]; - } - - protected function queryStage(array $validated): mixed - { - /** @var ContentNodeRangeArgs $args */ - $args = $validated['args']; - - $query = SiteContent::query() - ->select('site_content.*') - ->childrenRangeOf($args->id, $args->from, $args->to) - ->where('site_content.deleted', 0) - ->orderBy('site_content.menuindex', 'asc') - ->orderBy('site_content.id', 'asc'); - - $this->applyManagerAccess($query); - - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries); - } - - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); - } - - /** - * @return array - */ - protected function mapStage(mixed $queryResult, array $validated): array - { - /** @var ContentNodeRangeArgs $args */ - $args = $validated['args']; - - return [ - 'items' => $this->projectItems(is_iterable($queryResult) ? $queryResult : [], $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, - ]; - } - - protected function respondStage(array $mapped, array $validated): ResponseFactory - { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); - } - - /** - * @return array - */ - public function schema(JsonSchema $schema): array - { - return [ - 'id' => $schema->integer()->min(1)->required(), - 'from' => $schema->integer()->min(0)->required(), - 'to' => $schema->integer()->min(0)->nullable(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), - ]; - } -} diff --git a/src/Tools/Content/ContentChildrenTool.php b/src/Tools/Content/ContentChildrenTool.php deleted file mode 100644 index 0665679..0000000 --- a/src/Tools/Content/ContentChildrenTool.php +++ /dev/null @@ -1,107 +0,0 @@ - - */ - protected function validateStage(Request $request): array - { - $validated = $request->validate([ - 'id' => ['required', 'integer', 'min:1'], - 'with_tvs' => ['nullable', 'array'], - 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], - 'offset' => ['nullable', 'integer', 'min:0'], - ]); - - [$limit, $offset] = $this->resolveLimitOffset($validated); - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); - - return [ - 'args' => new ContentNodeListArgs( - (int)$validated['id'], - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'] - ), - ]; - } - - protected function queryStage(array $validated): mixed - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - $query = SiteContent::query() - ->select('site_content.*') - ->where('site_content.parent', $args->id) - ->where('site_content.deleted', 0) - ->orderBy('site_content.menuindex', 'asc') - ->orderBy('site_content.id', 'asc'); - - $this->applyManagerAccess($query); - - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries); - } - - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); - } - - /** - * @return array - */ - protected function mapStage(mixed $queryResult, array $validated): array - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - return [ - 'items' => $this->projectItems($queryResult, $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, - ]; - } - - protected function respondStage(array $mapped, array $validated): ResponseFactory - { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); - } - - /** - * @return array - */ - public function schema(JsonSchema $schema): array - { - return [ - 'id' => $schema->integer()->min(1)->required(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), - ]; - } -} diff --git a/src/Tools/Content/ContentDescendantsTool.php b/src/Tools/Content/ContentDescendantsTool.php deleted file mode 100644 index b86d5e2..0000000 --- a/src/Tools/Content/ContentDescendantsTool.php +++ /dev/null @@ -1,115 +0,0 @@ - - */ - protected function validateStage(Request $request): array - { - $validated = $request->validate([ - 'id' => ['required', 'integer', 'min:1'], - 'depth' => ['nullable', 'integer', 'min:1'], - 'with_tvs' => ['nullable', 'array'], - 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], - 'offset' => ['nullable', 'integer', 'min:0'], - ]); - - [$limit, $offset] = $this->resolveLimitOffset($validated); - $depth = $this->resolveDepth( - isset($validated['depth']) ? (int)$validated['depth'] : null - ); - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); - - return [ - 'args' => new ContentNodeListArgs( - (int)$validated['id'], - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'], - $depth - ), - ]; - } - - protected function queryStage(array $validated): mixed - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - $query = SiteContent::query() - ->select('site_content.*') - ->descendantsOf($args->id) - ->where('site_content_closure.depth', '<=', (int)$args->depth) - ->where('site_content.deleted', 0) - ->orderBy('site_content.parent', 'asc') - ->orderBy('site_content.menuindex', 'asc') - ->orderBy('site_content.id', 'asc'); - - $this->applyManagerAccess($query); - - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries); - } - - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); - } - - /** - * @return array - */ - protected function mapStage(mixed $queryResult, array $validated): array - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - return [ - 'items' => $this->projectItems($queryResult, $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, - ]; - } - - protected function respondStage(array $mapped, array $validated): ResponseFactory - { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); - } - - /** - * @return array - */ - public function schema(JsonSchema $schema): array - { - return [ - 'id' => $schema->integer()->min(1)->required(), - 'depth' => $schema->integer()->min(1)->nullable(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), - ]; - } -} diff --git a/src/Tools/Content/ContentGetTool.php b/src/Tools/Content/ContentGetTool.php index e02abca..1aa2186 100644 --- a/src/Tools/Content/ContentGetTool.php +++ b/src/Tools/Content/ContentGetTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\Content; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Contracts\ToolArguments\ContentGetArgs; use EvolutionCMS\Models\SiteContent; use Illuminate\Contracts\JsonSchema\JsonSchema; @@ -13,7 +15,8 @@ use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.content.get')] -#[Description('Get one content document by id, including its body (content, introtext, menutitle) and optional TVs projection.')] +#[Description('Read one visible document by ID, including its body, introtext, menutitle and requested TVs. Returns item null when the document is missing or inaccessible. Use evo.content.search when the ID is unknown.')] +/** Return a single document with detail fields and optional TV values. */ class ContentGetTool extends BaseContentTool { /** @@ -95,7 +98,19 @@ protected function respondStage(array $mapped, array $validated): ResponseFactor public function schema(JsonSchema $schema): array { return [ - 'id' => $schema->integer()->min(1)->required(), + 'id' => $schema->integer()->min(1)->required()->description('ID of the document to read.'), + 'with_tvs' => $this->tvSchema($schema), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::item($schema); + } } diff --git a/src/Tools/Content/ContentNeighborsTool.php b/src/Tools/Content/ContentNeighborsTool.php deleted file mode 100644 index a950aa1..0000000 --- a/src/Tools/Content/ContentNeighborsTool.php +++ /dev/null @@ -1,108 +0,0 @@ - - */ - protected function validateStage(Request $request): array - { - $validated = $request->validate([ - 'id' => ['required', 'integer', 'min:1'], - 'with_tvs' => ['nullable', 'array'], - 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], - 'offset' => ['nullable', 'integer', 'min:0'], - ]); - - [$limit, $offset] = $this->resolveLimitOffset($validated); - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); - - return [ - 'args' => new ContentNodeListArgs( - (int)$validated['id'], - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'] - ), - ]; - } - - protected function queryStage(array $validated): mixed - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - $query = SiteContent::query() - ->select('site_content.*') - ->neighborsOf($args->id) - ->where('site_content.id', '!=', $args->id) - ->where('site_content.deleted', 0) - ->orderBy('site_content.menuindex', 'asc') - ->orderBy('site_content.id', 'asc'); - - $this->applyManagerAccess($query); - - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries); - } - - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); - } - - /** - * @return array - */ - protected function mapStage(mixed $queryResult, array $validated): array - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - return [ - 'items' => $this->projectItems(is_iterable($queryResult) ? $queryResult : [], $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, - ]; - } - - protected function respondStage(array $mapped, array $validated): ResponseFactory - { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); - } - - /** - * @return array - */ - public function schema(JsonSchema $schema): array - { - return [ - 'id' => $schema->integer()->min(1)->required(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), - ]; - } -} diff --git a/src/Tools/Content/ContentNextSiblingsTool.php b/src/Tools/Content/ContentNextSiblingsTool.php deleted file mode 100644 index 1cdd6b0..0000000 --- a/src/Tools/Content/ContentNextSiblingsTool.php +++ /dev/null @@ -1,107 +0,0 @@ - - */ - protected function validateStage(Request $request): array - { - $validated = $request->validate([ - 'id' => ['required', 'integer', 'min:1'], - 'with_tvs' => ['nullable', 'array'], - 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], - 'offset' => ['nullable', 'integer', 'min:0'], - ]); - - [$limit, $offset] = $this->resolveLimitOffset($validated); - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); - - return [ - 'args' => new ContentNodeListArgs( - (int)$validated['id'], - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'] - ), - ]; - } - - protected function queryStage(array $validated): mixed - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - $query = SiteContent::query() - ->select('site_content.*') - ->nextSiblingsOf($args->id) - ->where('site_content.deleted', 0) - ->orderBy('site_content.menuindex', 'asc') - ->orderBy('site_content.id', 'asc'); - - $this->applyManagerAccess($query); - - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries); - } - - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); - } - - /** - * @return array - */ - protected function mapStage(mixed $queryResult, array $validated): array - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - return [ - 'items' => $this->projectItems(is_iterable($queryResult) ? $queryResult : [], $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, - ]; - } - - protected function respondStage(array $mapped, array $validated): ResponseFactory - { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); - } - - /** - * @return array - */ - public function schema(JsonSchema $schema): array - { - return [ - 'id' => $schema->integer()->min(1)->required(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), - ]; - } -} diff --git a/src/Tools/Content/ContentPrevSiblingsTool.php b/src/Tools/Content/ContentPrevSiblingsTool.php deleted file mode 100644 index 45db187..0000000 --- a/src/Tools/Content/ContentPrevSiblingsTool.php +++ /dev/null @@ -1,107 +0,0 @@ - - */ - protected function validateStage(Request $request): array - { - $validated = $request->validate([ - 'id' => ['required', 'integer', 'min:1'], - 'with_tvs' => ['nullable', 'array'], - 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], - 'offset' => ['nullable', 'integer', 'min:0'], - ]); - - [$limit, $offset] = $this->resolveLimitOffset($validated); - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); - - return [ - 'args' => new ContentNodeListArgs( - (int)$validated['id'], - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'] - ), - ]; - } - - protected function queryStage(array $validated): mixed - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - $query = SiteContent::query() - ->select('site_content.*') - ->prevSiblingsOf($args->id) - ->where('site_content.deleted', 0) - ->orderBy('site_content.menuindex', 'desc') - ->orderBy('site_content.id', 'desc'); - - $this->applyManagerAccess($query); - - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries); - } - - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); - } - - /** - * @return array - */ - protected function mapStage(mixed $queryResult, array $validated): array - { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - return [ - 'items' => $this->projectItems(is_iterable($queryResult) ? $queryResult : [], $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, - ]; - } - - protected function respondStage(array $mapped, array $validated): ResponseFactory - { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); - } - - /** - * @return array - */ - public function schema(JsonSchema $schema): array - { - return [ - 'id' => $schema->integer()->min(1)->required(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), - ]; - } -} diff --git a/src/Tools/Content/ContentRootTreeTool.php b/src/Tools/Content/ContentRootTreeTool.php deleted file mode 100644 index 9724527..0000000 --- a/src/Tools/Content/ContentRootTreeTool.php +++ /dev/null @@ -1,108 +0,0 @@ - - */ - protected function validateStage(Request $request): array - { - $validated = $request->validate([ - 'depth' => ['nullable', 'integer', 'min:1'], - 'with_tvs' => ['nullable', 'array'], - 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], - 'offset' => ['nullable', 'integer', 'min:0'], - ]); - - [$limit, $offset] = $this->resolveLimitOffset($validated); - $depth = $this->resolveDepth( - isset($validated['depth']) ? (int)$validated['depth'] : null - ); - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); - - return [ - 'args' => new ContentRootTreeArgs( - $depth, - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'] - ), - ]; - } - - protected function queryStage(array $validated): mixed - { - /** @var ContentRootTreeArgs $args */ - $args = $validated['args']; - - $query = SiteContent::query() - ->getRootTree($args->depth + 1) - ->where('t2.deleted', 0) - ->orderBy('t2.id', 'asc'); - - $this->applyManagerAccess($query, 't2'); - - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries, ':', true); - } - - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); - } - - /** - * @return array - */ - protected function mapStage(mixed $queryResult, array $validated): array - { - /** @var ContentRootTreeArgs $args */ - $args = $validated['args']; - - return [ - 'items' => $this->projectItems($queryResult, $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, - ]; - } - - protected function respondStage(array $mapped, array $validated): ResponseFactory - { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); - } - - /** - * @return array - */ - public function schema(JsonSchema $schema): array - { - return [ - 'depth' => $schema->integer()->min(1)->nullable(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), - ]; - } -} diff --git a/src/Tools/Content/ContentSearchTool.php b/src/Tools/Content/ContentSearchTool.php index fa39617..837387e 100644 --- a/src/Tools/Content/ContentSearchTool.php +++ b/src/Tools/Content/ContentSearchTool.php @@ -14,7 +14,8 @@ use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.content.search')] -#[Description('Search Evolution CMS content with pagination, depth caps, and structured TV filters/order.')] +#[Description('Search visible documents using field filters, template, publication state, TV values or tags. Use evo.content.get for a known ID or evo.content.tree for a fixed tree relationship.')] +/** Search accessible documents using structured filters and deterministic paging. */ class ContentSearchTool extends BaseContentTool { /** @@ -169,14 +170,41 @@ protected function respondStage(array $mapped, array $validated): ResponseFactor */ public function schema(JsonSchema $schema): array { + $direction = ['asc', 'desc']; + return [ - 'limit' => $schema->integer()->min(1), - 'offset' => $schema->integer()->min(0)->nullable(), - 'parent' => $schema->integer()->min(0)->nullable(), - 'depth' => $schema->integer()->min(1)->nullable(), - 'order_by' => $schema->string()->nullable(), - 'order_dir' => $schema->string()->nullable(), - 'order_by_date' => $schema->string()->nullable(), - ]; + 'parent' => $schema->integer()->min(0)->nullable() + ->description('Ancestor ID to scope the search to its descendants. Omit to search the site.'), + 'published' => $schema->boolean()->nullable()->description('Filter by publication state, subject to caller visibility.'), + 'deleted' => $schema->boolean()->nullable()->default(false)->description('Select trashed documents when true. Defaults to live documents.'), + 'template' => $schema->integer()->min(0)->nullable()->description('Filter by template ID.'), + 'hidemenu' => $schema->boolean()->nullable()->description('Filter by the Hide from menu flag.'), + 'depth' => $schema->integer()->min(1)->nullable() + ->description('Maximum levels below parent. Used only with parent and defaults to the server depth limit.'), + 'with_tvs' => $this->tvSchema($schema), + 'tv_filters' => $schema->array()->nullable()->items($schema->object([ + 'tv' => $schema->string()->required()->description('TV name.'), + 'op' => $schema->string()->enum(self::ALLOWED_TV_OPERATORS)->required()->description('Comparison operator.'), + 'value' => $schema->union(['string', 'number', 'boolean', 'array'])->nullable() + ->description('Operand; omit for null or !null. in and not_in accept a list.'), + 'cast' => $schema->string()->nullable()->description('Optional numeric comparison cast: SIGNED, UNSIGNED or DECIMAL(p,s).'), + 'use_default' => $schema->boolean()->nullable()->default(false)->description('Use the TV default when no document value is stored.'), + ]))->description('TV conditions. Example: [{"tv":"price","op":">","value":"100","cast":"UNSIGNED"}].'), + 'tv_order' => $schema->array()->nullable()->items($schema->object([ + 'tv' => $schema->string()->required()->description('TV name.'), + 'dir' => $schema->string()->enum([...$direction, null])->nullable()->default('asc')->description('TV sort direction.'), + 'cast' => $schema->string()->enum([...self::ALLOWED_TV_CASTS, null])->nullable()->description('Optional numeric TV sort cast.'), + 'use_default' => $schema->boolean()->nullable()->default(false)->description('Use the TV default when no document value is stored.'), + ]))->description('Ordered TV sort keys. Example: [{"tv":"price","dir":"asc","cast":"UNSIGNED"}].'), + 'tags_data' => $schema->object([ + 'tv_id' => $schema->integer()->min(1)->required()->description('ID of the tag TV.'), + 'tags' => $schema->array()->items($schema->string())->required()->description('Nonempty list of tag values.'), + ])->nullable()->description('Tag match. Example: {"tv_id":17,"tags":["sale","featured"]}.'), + 'order_by' => $schema->string()->enum([...self::ALLOWED_SORT_FIELDS, null])->nullable() + ->description('Document sort field after TV sorting. Defaults to id ascending.'), + 'order_dir' => $schema->string()->enum([...$direction, null])->nullable()->description('Direction for order_by; defaults to asc.'), + 'order_by_date' => $schema->string()->enum([...$direction, null])->nullable() + ->description('Sort by publication date or creation date when no publication date is set. Takes precedence over order_by.'), + ] + $this->pagingSchema($schema); } } diff --git a/src/Tools/Content/ContentSiblingsRangeTool.php b/src/Tools/Content/ContentSiblingsRangeTool.php deleted file mode 100644 index 8b1704b..0000000 --- a/src/Tools/Content/ContentSiblingsRangeTool.php +++ /dev/null @@ -1,123 +0,0 @@ - - */ - protected function validateStage(Request $request): array - { - $validated = $request->validate([ - 'id' => ['required', 'integer', 'min:1'], - 'from' => ['required', 'integer', 'min:0'], - 'to' => ['nullable', 'integer', 'min:0'], - 'with_tvs' => ['nullable', 'array'], - 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], - 'offset' => ['nullable', 'integer', 'min:0'], - ]); - - $from = (int)$validated['from']; - $to = isset($validated['to']) ? (int)$validated['to'] : null; - if ($to !== null && $to < $from) { - throw ValidationException::withMessages([ - 'to' => 'to must be greater than or equal to from.', - ]); - } - - [$limit, $offset] = $this->resolveLimitOffset($validated); - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); - - return [ - 'args' => new ContentNodeRangeArgs( - (int)$validated['id'], - $from, - $to, - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'] - ), - ]; - } - - protected function queryStage(array $validated): mixed - { - /** @var ContentNodeRangeArgs $args */ - $args = $validated['args']; - - $query = SiteContent::query() - ->select('site_content.*') - ->siblingsRangeOf($args->id, $args->from, $args->to) - ->where('site_content.id', '!=', $args->id) - ->where('site_content.deleted', 0) - ->orderBy('site_content.menuindex', 'asc') - ->orderBy('site_content.id', 'asc'); - - $this->applyManagerAccess($query); - - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries); - } - - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); - } - - /** - * @return array - */ - protected function mapStage(mixed $queryResult, array $validated): array - { - /** @var ContentNodeRangeArgs $args */ - $args = $validated['args']; - - return [ - 'items' => $this->projectItems(is_iterable($queryResult) ? $queryResult : [], $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, - ]; - } - - protected function respondStage(array $mapped, array $validated): ResponseFactory - { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); - } - - /** - * @return array - */ - public function schema(JsonSchema $schema): array - { - return [ - 'id' => $schema->integer()->min(1)->required(), - 'from' => $schema->integer()->min(0)->required(), - 'to' => $schema->integer()->min(0)->nullable(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), - ]; - } -} diff --git a/src/Tools/Content/ContentSiblingsTool.php b/src/Tools/Content/ContentSiblingsTool.php index a071414..1c0c25d 100644 --- a/src/Tools/Content/ContentSiblingsTool.php +++ b/src/Tools/Content/ContentSiblingsTool.php @@ -4,116 +4,141 @@ namespace EvolutionCMS\eMCP\Tools\Content; -use EvolutionCMS\eMCP\Contracts\ToolArguments\ContentNodeListArgs; -use EvolutionCMS\eMCP\Contracts\ToolArguments\PagingArgs; use EvolutionCMS\Models\SiteContent; use Illuminate\Contracts\JsonSchema\JsonSchema; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Validation\ValidationException; use Laravel\Mcp\Request; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Attributes\Description; use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.content.siblings')] -#[Description('Read sibling documents of a content node with pagination.')] +#[Description('List visible documents sharing the anchor’s parent, excluding the anchor. Select all, before, after, or the closest document in each direction. Use evo.content.tree for children or deeper descendants.')] +/** Navigate within the anchor’s sibling set by menuindex and document ID. */ class ContentSiblingsTool extends BaseContentTool { - /** - * @return array - */ + private const DIRECTIONS = ['all', 'before', 'after', 'adjacent']; + + /** Require pagination for list modes and restrict menuindex bounds to all. */ protected function validateStage(Request $request): array { $validated = $request->validate([ 'id' => ['required', 'integer', 'min:1'], + 'direction' => ['sometimes', 'required', 'in:' . implode(',', self::DIRECTIONS)], + 'menuindex_from' => ['nullable', 'integer', 'min:0'], + 'menuindex_to' => ['nullable', 'integer', 'min:0'], 'with_tvs' => ['nullable', 'array'], 'with_tvs.*' => ['string'], - 'limit' => ['required', 'integer', 'min:1'], + 'limit' => ['sometimes', 'required', 'integer', 'min:1'], 'offset' => ['nullable', 'integer', 'min:0'], ]); - [$limit, $offset] = $this->resolveLimitOffset($validated); - $withTvs = $this->normalizeWithTvs($validated['with_tvs'] ?? null); + $direction = $validated['direction'] ?? 'all'; + $from = isset($validated['menuindex_from']) ? (int)$validated['menuindex_from'] : null; + $to = isset($validated['menuindex_to']) ? (int)$validated['menuindex_to'] : null; + if ($direction !== 'all' && ($from !== null || $to !== null)) { + throw ValidationException::withMessages(['direction' => 'Menuindex bounds require direction all.']); + } + $this->validateMenuindexRange($from, $to); + + if ($direction === 'adjacent') { + if (isset($validated['limit']) || isset($validated['offset'])) { + throw ValidationException::withMessages(['direction' => 'Adjacent results do not support limit or offset.']); + } + [$limit, $offset] = [2, 0]; + } else { + if (!isset($validated['limit'])) { + throw ValidationException::withMessages(['limit' => 'A limit is required for all, before and after.']); + } + [$limit, $offset] = $this->resolveLimitOffset($validated); + } - return [ - 'args' => new ContentNodeListArgs( - (int)$validated['id'], - new PagingArgs($limit, $offset), - $withTvs['entries'], - $withTvs['names'] - ), + return compact('direction', 'from', 'to', 'limit', 'offset') + [ + 'id' => (int)$validated['id'], + 'tvs' => $this->normalizeWithTvs($validated['with_tvs'] ?? null), ]; } - protected function queryStage(array $validated): mixed + /** Scope both the anchor and the returned siblings to documents visible to the caller. */ + protected function queryStage(array $validated): iterable { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; - - /** @var SiteContent|null $node */ - $node = SiteContent::query() - ->select('id', 'parent') - ->where('id', $args->id) - ->where('deleted', 0) - ->first(); - - if ($node === null) { + $anchor = $this->findAnchor($validated['id']); + if ($anchor === null) { return []; } - $query = SiteContent::query() - ->select('site_content.*') - ->where('site_content.parent', (int)$node->getAttribute('parent')) - ->where('site_content.id', '!=', $args->id) - ->where('site_content.deleted', 0) - ->orderBy('site_content.menuindex', 'asc') - ->orderBy('site_content.id', 'asc'); - + $query = SiteContent::query()->select('site_content.*') + ->where('site_content.parent', $anchor->parent) + ->where('site_content.id', '!=', $anchor->id) + ->where('site_content.deleted', 0); $this->applyManagerAccess($query); + if ($validated['tvs']['entries'] !== []) { + $query->withTVs($validated['tvs']['entries']); + } + + $direction = $validated['direction']; + if ($direction === 'adjacent') { + $previous = $this->inDirection(clone $query, $anchor, 'before')->first(); + $next = $this->inDirection($query, $anchor, 'after')->first(); - if ($args->withTvEntries !== []) { - $query->withTVs($args->withTvEntries); + return array_values(array_filter([$previous, $next])); } - return $query - ->limit($args->paging->limit) - ->offset($args->paging->offset) - ->get(); + if ($direction === 'all') { + $this->applyMenuindexRange($query, 'site_content', $validated['from'], $validated['to']); + $query->orderBy('site_content.menuindex')->orderBy('site_content.id'); + } else { + $this->inDirection($query, $anchor, $direction); + } + + return $query->limit($validated['limit'])->offset($validated['offset'])->get(); } /** - * @return array + * Seek away from the anchor in one direction, using ID to break menuindex ties. + * + * @since 0.3.0 */ - protected function mapStage(mixed $queryResult, array $validated): array + private function inDirection(Builder $query, SiteContent $anchor, string $direction): Builder { - /** @var ContentNodeListArgs $args */ - $args = $validated['args']; + $before = $direction === 'before'; + $operator = $before ? '<' : '>'; + $order = $before ? 'desc' : 'asc'; + + return $query->where(function (Builder $query) use ($anchor, $operator): void { + $query->where('site_content.menuindex', $operator, $anchor->menuindex) + ->orWhere(function (Builder $tie) use ($anchor, $operator): void { + $tie->where('site_content.menuindex', $anchor->menuindex) + ->where('site_content.id', $operator, $anchor->id); + }); + })->orderBy('site_content.menuindex', $order)->orderBy('site_content.id', $order); + } - return [ - 'items' => $this->projectItems(is_iterable($queryResult) ? $queryResult : [], $args->withTvNames), - 'limit' => $args->paging->limit, - 'offset' => $args->paging->offset, - ]; + /** Project the page of siblings or the nearest two visible records. */ + protected function mapStage(mixed $queryResult, array $validated): array + { + return ['items' => $this->projectItems($queryResult, $validated['tvs']['names'])]; } + /** Use the same structured list envelope in every direction. */ protected function respondStage(array $mapped, array $validated): ResponseFactory { - $items = is_array($mapped['items'] ?? null) ? $mapped['items'] : []; - - return $this->respondList( - $items, - (int)($mapped['limit'] ?? 0), - (int)($mapped['offset'] ?? 0) - ); + return $this->respondList($mapped['items'], $validated['limit'], $validated['offset']); } - /** - * @return array - */ + /** Describe the direction-specific constraints alongside the shared list arguments. */ public function schema(JsonSchema $schema): array { return [ - 'id' => $schema->integer()->min(1)->required(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), + 'id' => $schema->integer()->min(1)->required()->description('ID of the visible document whose siblings to read.'), + 'direction' => $schema->string()->enum(self::DIRECTIONS)->default('all') + ->description('all uses ascending (menuindex, id); before and after start with the nearest match; adjacent returns at most one per side.'), + 'menuindex_from' => $schema->integer()->min(0)->nullable()->description('Inclusive lower menuindex bound, for all only.'), + 'menuindex_to' => $schema->integer()->min(0)->nullable()->description('Inclusive upper menuindex bound, for all only.'), + 'with_tvs' => $this->tvSchema($schema), + 'limit' => $schema->integer()->min(1)->description('Required for all, before and after. Omit for adjacent.'), + 'offset' => $schema->integer()->min(0)->nullable()->description('Matching records to skip. Defaults to 0 for paged directions. Omit for adjacent.'), ]; } } diff --git a/src/Tools/Content/ContentTreeTool.php b/src/Tools/Content/ContentTreeTool.php new file mode 100644 index 0000000..a28f383 --- /dev/null +++ b/src/Tools/Content/ContentTreeTool.php @@ -0,0 +1,134 @@ + + * @since 0.3.0 + */ + protected function validateStage(Request $request): array + { + $validated = $request->validate([ + 'id' => ['required', 'integer', 'min:0'], + 'depth' => ['nullable', 'integer', 'min:1'], + 'menuindex_from' => ['nullable', 'integer', 'min:0'], + 'menuindex_to' => ['nullable', 'integer', 'min:0'], + 'with_tvs' => ['nullable', 'array'], + 'with_tvs.*' => ['string'], + 'limit' => ['required', 'integer', 'min:1'], + 'offset' => ['nullable', 'integer', 'min:0'], + ]); + + $id = (int)$validated['id']; + $depth = (int)($validated['depth'] ?? 1); + $maxDepth = $this->resolveMaxDepth() + ($id === 0 ? 1 : 0); + if ($depth > $maxDepth) { + throw ValidationException::withMessages(['depth' => "depth must be between 1 and {$maxDepth} for this anchor."]); + } + + $from = isset($validated['menuindex_from']) ? (int)$validated['menuindex_from'] : null; + $to = isset($validated['menuindex_to']) ? (int)$validated['menuindex_to'] : null; + if ($depth !== 1 && ($from !== null || $to !== null)) { + throw ValidationException::withMessages(['depth' => 'A menuindex range requires depth 1.']); + } + $this->validateMenuindexRange($from, $to); + [$limit, $offset] = $this->resolveLimitOffset($validated); + + return compact('id', 'depth', 'from', 'to', 'limit', 'offset') + + ['tvs' => $this->normalizeWithTvs($validated['with_tvs'] ?? null)]; + } + + /** + * Apply the traversal and access filters before pagination. + * + * @since 0.3.0 + */ + protected function queryStage(array $validated): iterable + { + ['id' => $id, 'depth' => $depth, 'from' => $from, 'to' => $to, 'tvs' => $tvs] = $validated; + + if ($id !== 0 && $this->findAnchor($id) === null) { + return []; + } + + $query = SiteContent::query()->select('site_content.*'); + $table = 'site_content'; + if ($depth === 1) { + $query->where('site_content.parent', $id); + } elseif ($id === 0) { + $query->getRootTree($depth); + $table = 't2'; + } else { + $query->descendantsOf($id)->where('site_content_closure.depth', '<=', $depth); + } + + $query->where($table . '.deleted', 0); + $this->applyManagerAccess($query, $table); + $this->applyMenuindexRange($query, $table, $from, $to); + if ($tvs['entries'] !== []) { + $query->withTVs($tvs['entries'], ':', $table === 't2'); + } + + return $query->orderBy($table . '.parent')->orderBy($table . '.menuindex')->orderBy($table . '.id') + ->limit($validated['limit'])->offset($validated['offset'])->get(); + } + + /** + * Project only the public resource columns and requested TVs. + * + * @since 0.3.0 + */ + protected function mapStage(mixed $queryResult, array $validated): array + { + return ['items' => $this->projectItems($queryResult, $validated['tvs']['names'])]; + } + + /** + * Return the page and the paging values applied to it. + * + * @since 0.3.0 + */ + protected function respondStage(array $mapped, array $validated): ResponseFactory + { + return $this->respondList($mapped['items'], $validated['limit'], $validated['offset']); + } + + /** + * Advertise the tree-specific options and common paging and TV arguments. + * + * @return array + * @since 0.3.0 + */ + public function schema(JsonSchema $schema): array + { + return [ + 'id' => $schema->integer()->min(0)->required()->description('Document ID, or 0 for the virtual site root.'), + 'depth' => $schema->integer()->min(1)->nullable()->default(1) + ->description('Levels below the anchor, up to the configured maximum. At 0, depth 1 returns top-level documents.'), + 'menuindex_from' => $schema->integer()->min(0)->nullable()->description('Inclusive lower menuindex bound, only at depth 1.'), + 'menuindex_to' => $schema->integer()->min(0)->nullable()->description('Inclusive upper menuindex bound, only at depth 1.'), + 'with_tvs' => $this->tvSchema($schema), + ] + $this->pagingSchema($schema); + } +} diff --git a/src/Tools/Elements/ElementsGetTool.php b/src/Tools/Elements/ElementsGetTool.php index 32764ee..2094398 100644 --- a/src/Tools/Elements/ElementsGetTool.php +++ b/src/Tools/Elements/ElementsGetTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\Elements; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Support\ElementTypes; use EvolutionCMS\eMCP\Tools\Write\BaseWriteTool; use Illuminate\Contracts\JsonSchema\JsonSchema; @@ -15,7 +17,8 @@ use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.elements.get')] -#[Description('Read one template, TV, chunk, snippet or plugin including its code, by id or name.')] +#[Description('Read one editable template, TV, chunk, snippet or plugin by ID or exact name, including source and lock information. Use evo.elements.list to browse elements or evo.content.get to read a document.')] +/** Read the fields and source of one element allowed by the manager role. */ class ElementsGetTool extends BaseWriteTool { public function handle(Request $request): ResponseFactory @@ -71,9 +74,20 @@ public static function find(array $spec, ?int $id, ?string $name): ?Model public function schema(JsonSchema $schema): array { return [ - 'type' => $schema->string()->enum(ElementTypes::names())->required(), - 'id' => $schema->integer()->min(1), - 'name' => $schema->string()->description('Exact element name, used when id is omitted'), + 'type' => $schema->string()->enum(ElementTypes::names())->required()->description('Element type, which determines the required edit permission.'), + 'id' => $schema->integer()->min(1)->nullable()->description('Element ID. Takes precedence over name even if it does not match a record.'), + 'name' => $schema->string()->max(255)->nullable()->description('Exact element name; required when id is omitted.'), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::item($schema); + } } diff --git a/src/Tools/Elements/ElementsListTool.php b/src/Tools/Elements/ElementsListTool.php index 49b6233..66501e2 100644 --- a/src/Tools/Elements/ElementsListTool.php +++ b/src/Tools/Elements/ElementsListTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\Elements; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Contracts\ToolResponses\ListToolResponse; use EvolutionCMS\eMCP\Support\ElementTypes; use EvolutionCMS\eMCP\Tools\Write\BaseWriteTool; @@ -16,7 +18,8 @@ use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.elements.list')] -#[Description('List templates, TVs, chunks, snippets or plugins (without code) the acting user may edit.')] +#[Description('List editable templates, TVs, chunks, snippets or plugins ordered by name, with lock information. Requires the edit permission for the type. Use evo.elements.get for one element and its source code.')] +/** Read a paginated, code-free list of elements of one type. */ class ElementsListTool extends BaseWriteTool { public function handle(Request $request): ResponseFactory @@ -66,7 +69,7 @@ public function handle(Request $request): ResponseFactory $limit, $offset, count($items), - (string)config('cms.settings.eMCP.toolset_version', '1.0') + ToolContract::VERSION ))->toArray() ); } @@ -84,11 +87,22 @@ private function lockedBy(int $type, int $id): ?string public function schema(JsonSchema $schema): array { return [ - 'type' => $schema->string()->enum(ElementTypes::names())->required(), - 'search' => $schema->string()->description('Substring of the element name'), - 'category' => $schema->integer()->min(0), - 'limit' => $schema->integer()->min(1)->description('Default 50, max 200'), - 'offset' => $schema->integer()->min(0), + 'type' => $schema->string()->enum(ElementTypes::names())->required()->description('Element type to list.'), + 'search' => $schema->string()->max(100)->nullable()->description('Substring of the element name. Omit for all names.'), + 'category' => $schema->integer()->min(0)->nullable()->description('Category ID. Omit for any category.'), + 'limit' => $schema->integer()->min(1)->max(200)->nullable()->default(50)->description('Maximum matching elements to return.'), + 'offset' => $schema->integer()->min(0)->nullable()->default(0)->description('Matching elements to skip after sorting by name.'), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::listing($schema); + } } diff --git a/src/Tools/ModelCatalog/BaseModelTool.php b/src/Tools/ModelCatalog/BaseModelTool.php index dec98da..ee29eb1 100644 --- a/src/Tools/ModelCatalog/BaseModelTool.php +++ b/src/Tools/ModelCatalog/BaseModelTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\ModelCatalog; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Contracts\ToolResponses\ItemToolResponse; use EvolutionCMS\eMCP\Contracts\ToolResponses\ListToolResponse; use EvolutionCMS\eMCP\Mappers\ModelRecordMapper; @@ -337,7 +339,7 @@ protected function respondList(string $modelClass, array $items, int $limit, int $limit, $offset, count($items), - (string)config('cms.settings.eMCP.toolset_version', '1.0'), + ToolContract::VERSION, class_basename($modelClass) ))->toArray() ); @@ -351,7 +353,7 @@ protected function respondItem(string $modelClass, ?array $item): ResponseFactor return Response::structured( (new ItemToolResponse( $item, - (string)config('cms.settings.eMCP.toolset_version', '1.0'), + ToolContract::VERSION, class_basename($modelClass) ))->toArray() ); diff --git a/src/Tools/ModelCatalog/ModelGetTool.php b/src/Tools/ModelCatalog/ModelGetTool.php index 866c68f..086c8f1 100644 --- a/src/Tools/ModelCatalog/ModelGetTool.php +++ b/src/Tools/ModelCatalog/ModelGetTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\ModelCatalog; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Contracts\ToolArguments\ModelGetArgs; use Illuminate\Contracts\JsonSchema\JsonSchema; use Illuminate\Database\Eloquent\Model; @@ -13,7 +15,8 @@ use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.model.get')] -#[Description('Get one allowlisted Evolution CMS model record by id with allowlist projection.')] +#[Description('Read one record by ID from an allowed Evolution CMS model. Requires permission to read that model and returns only its public fields. Use evo.model.list to filter or browse several records.')] +/** Read one projected record from a registered model. */ class ModelGetTool extends BaseModelTool { /** @@ -85,8 +88,21 @@ protected function respondStage(array $mapped, array $validated): ResponseFactor public function schema(JsonSchema $schema): array { return [ - 'model' => $schema->string()->required(), - 'id' => $schema->integer()->min(1)->required(), + 'model' => $schema->string()->required()->description('Allowed model alias or full class name, case-insensitive. Unsupported models produce an error.'), + 'id' => $schema->integer()->min(1)->required()->description('Record ID. A missing record returns item null.'), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::item($schema, extraMeta: [ + 'model' => $schema->string()->required()->description('Canonical short name of the queried model.'), + ]); + } } diff --git a/src/Tools/ModelCatalog/ModelListTool.php b/src/Tools/ModelCatalog/ModelListTool.php index 91b9baf..e476958 100644 --- a/src/Tools/ModelCatalog/ModelListTool.php +++ b/src/Tools/ModelCatalog/ModelListTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\ModelCatalog; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Contracts\ToolArguments\ModelListArgs; use EvolutionCMS\eMCP\Contracts\ToolArguments\PagingArgs; use Illuminate\Contracts\JsonSchema\JsonSchema; @@ -13,7 +15,8 @@ use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.model.list')] -#[Description('List allowlisted Evolution CMS models with explicit allowlist projection.')] +#[Description('List records from one allowed Evolution CMS model, optionally filtered and sorted by its public fields. Requires permission to read that model. Use evo.model.get for a known record ID or evo.elements.list for browsing editable CMS elements.')] +/** Read a page of projected records from one registered model. */ class ModelListTool extends BaseModelTool { /** @@ -108,11 +111,33 @@ protected function respondStage(array $mapped, array $validated): ResponseFactor public function schema(JsonSchema $schema): array { return [ - 'model' => $schema->string()->required(), - 'limit' => $schema->integer()->min(1)->required(), - 'offset' => $schema->integer()->min(0)->nullable(), - 'order_by' => $schema->string()->nullable(), - 'order_dir' => $schema->string()->nullable(), + 'model' => $schema->string()->required() + ->description('Allowed model alias or full class name, case-insensitive. Unsupported models or missing read permissions produce an error.'), + 'filters' => $schema->object([ + 'where' => $schema->array()->items($schema->object([ + 'field' => $schema->string()->required()->description('Allowlisted field of the selected model.'), + 'op' => $schema->string()->enum(self::ALLOWED_OPERATORS)->required()->description('Comparison operator.'), + 'value' => $schema->union(['string', 'number', 'boolean', 'array'])->nullable() + ->description('Scalar operand, or a list for in and not_in. Omit for null and !null.'), + ]))->nullable()->description('Conditions combined with AND.'), + ])->nullable()->description('Structured field filters. Example: {"where":[{"field":"name","op":"like","value":"banner"}]}.'), + 'limit' => $schema->integer()->min(1)->required()->description('Maximum records to return, up to the configured server limit.'), + 'offset' => $schema->integer()->min(0)->nullable()->default(0)->description('Number of matching records to skip after sorting.'), + 'order_by' => $schema->string()->nullable()->description('Allowlisted sort field. Defaults to id, or the first public field if id is unavailable.'), + 'order_dir' => $schema->string()->enum(['asc', 'desc', null])->nullable()->description('Direction for order_by. Defaults to asc.'), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::listing($schema, [ + 'model' => $schema->string()->required()->description('Canonical short name of the queried model.'), + ]); + } } diff --git a/src/Tools/Write/BaseWriteTool.php b/src/Tools/Write/BaseWriteTool.php index 9cb9146..3d36f04 100644 --- a/src/Tools/Write/BaseWriteTool.php +++ b/src/Tools/Write/BaseWriteTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\Write; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Contracts\ToolResponses\ItemToolResponse; use EvolutionCMS\Legacy\Permissions; use EvolutionCMS\Models\ManagerLog; @@ -124,7 +126,7 @@ protected function respondItem(?array $item): ResponseFactory return Response::structured( (new ItemToolResponse( $item, - (string)config('cms.settings.eMCP.toolset_version', '1.0') + ToolContract::VERSION ))->toArray() ); } diff --git a/src/Tools/Write/CacheClearTool.php b/src/Tools/Write/CacheClearTool.php index efab140..3ef4e1b 100644 --- a/src/Tools/Write/CacheClearTool.php +++ b/src/Tools/Write/CacheClearTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\Write; +use EvolutionCMS\eMCP\Support\ToolContract; + use Illuminate\Contracts\JsonSchema\JsonSchema; use Laravel\Mcp\Request; use Laravel\Mcp\ResponseFactory; @@ -11,7 +13,8 @@ use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.write.cache.clear')] -#[Description('Clear the site cache (same as "Refresh site" in the manager). Requires empty_cache.')] +#[Description('Clear the full site cache, as Refresh site does in the manager. Requires the Evo empty_cache permission. Takes no arguments and returns cleared on success.')] +/** Refresh the complete site cache for an authorized manager. */ class CacheClearTool extends BaseWriteTool { public function handle(Request $request): ResponseFactory @@ -31,4 +34,15 @@ public function schema(JsonSchema $schema): array { return []; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::item($schema, ['cleared' => $schema->boolean()->required()], nullable: false); + } } diff --git a/src/Tools/Write/ContentCreateTool.php b/src/Tools/Write/ContentCreateTool.php index 10e5fa2..a367d51 100644 --- a/src/Tools/Write/ContentCreateTool.php +++ b/src/Tools/Write/ContentCreateTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\Write; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\DocumentManager\Facades\DocumentManager; use EvolutionCMS\Exceptions\ServiceActionException; use EvolutionCMS\Exceptions\ServiceValidationException; @@ -18,6 +20,7 @@ #[Name('evo.write.content.create')] #[Description('Create a document under a parent. Requires new_document (and publish_document to create it published).')] +/** Create a document under an authorized parent and return its ID and state. */ class ContentCreateTool extends BaseWriteTool { public function handle(Request $request): ResponseFactory @@ -114,8 +117,27 @@ public function schema(JsonSchema $schema): array { return [ 'parent' => $schema->integer()->min(0)->required()->description('Parent document id, 0 for the site root'), - 'fields' => $schema->object()->required()->description('Document columns; pagetitle is required. Allowed: ' . implode(', ', ContentUpdateTool::WRITABLE_FIELDS)), - 'tvs' => $schema->object()->description('Template variable values keyed by TV name'), + 'fields' => $schema->object([ + 'pagetitle' => $schema->string()->required()->description('Title of the new document.'), + ])->required()->description('Document columns. Select the parent with the top-level parent argument. Allowed: ' . implode(', ', ContentUpdateTool::WRITABLE_FIELDS)), + 'tvs' => $schema->object()->nullable()->description('TV values keyed by name for the chosen template.'), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::item($schema, [ + 'id' => $schema->integer()->required(), + 'parent' => $schema->integer()->required(), + 'pagetitle' => $schema->string()->required(), + 'alias' => $schema->string()->nullable()->required(), + 'published' => $schema->boolean()->required(), + ], nullable: false); + } } diff --git a/src/Tools/Write/ContentPublishTool.php b/src/Tools/Write/ContentPublishTool.php index f79b81f..9cdc52c 100644 --- a/src/Tools/Write/ContentPublishTool.php +++ b/src/Tools/Write/ContentPublishTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\Write; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\DocumentManager\Facades\DocumentManager; use EvolutionCMS\Exceptions\ServiceActionException; use EvolutionCMS\Exceptions\ServiceValidationException; @@ -15,7 +17,8 @@ use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.write.content.publish')] -#[Description('Publish, unpublish, delete (to trash) or restore a document. Requires publish_document or delete_document.')] +#[Description('Publish, unpublish, move a document to the trash or restore it. Use evo.write.content.update to edit document fields, TVs and scheduled publication dates.')] +/** Apply a standalone document lifecycle action and report the resulting state. */ class ContentPublishTool extends BaseWriteTool { /** @var array */ @@ -71,8 +74,25 @@ public function handle(Request $request): ResponseFactory public function schema(JsonSchema $schema): array { return [ - 'id' => $schema->integer()->min(1)->required(), - 'action' => $schema->string()->enum(array_keys(self::ACTIONS))->required(), + 'id' => $schema->integer()->min(1)->required()->description('Document ID, including trashed documents when restoring.'), + 'action' => $schema->string()->enum(array_keys(self::ACTIONS))->required() + ->description('publish and unpublish require publish_document; delete and undelete require delete_document.'), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::item($schema, [ + 'id' => $schema->integer()->required(), + 'action' => $schema->string()->enum(array_keys(self::ACTIONS))->required(), + 'published' => $schema->boolean()->required(), + 'deleted' => $schema->boolean()->required(), + ], nullable: false); + } } diff --git a/src/Tools/Write/ContentUpdateTool.php b/src/Tools/Write/ContentUpdateTool.php index 4958503..9d719eb 100644 --- a/src/Tools/Write/ContentUpdateTool.php +++ b/src/Tools/Write/ContentUpdateTool.php @@ -4,11 +4,14 @@ namespace EvolutionCMS\eMCP\Tools\Write; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\DocumentManager\Facades\DocumentManager; use EvolutionCMS\Exceptions\ServiceActionException; use EvolutionCMS\Exceptions\ServiceValidationException; use EvolutionCMS\Models\SiteContent; use Illuminate\Contracts\JsonSchema\JsonSchema; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Validation\ValidationException; use Laravel\Mcp\Request; use Laravel\Mcp\ResponseFactory; @@ -16,7 +19,8 @@ use Laravel\Mcp\Server\Attributes\Name; #[Name('evo.write.content.update')] -#[Description('Update fields and TVs of an existing document. Requires save_document; publish state changes need publish_document.')] +#[Description('Update document fields and TVs together in one transaction. Requires the Evo save_document permission. Changing published, pub_date or unpub_date also requires publish_document. For a standalone publish or unpublish action use evo.write.content.publish.')] +/** Save a partial document update through the transactional DocumentManager API. */ class ContentUpdateTool extends BaseWriteTool { /** @var array */ @@ -24,19 +28,23 @@ class ContentUpdateTool extends BaseWriteTool 'pagetitle', 'longtitle', 'description', 'alias', 'introtext', 'content', 'menutitle', 'template', 'parent', 'published', 'pub_date', 'unpub_date', 'hidemenu', 'menuindex', 'isfolder', 'searchable', 'cacheable', 'richtext', 'type', 'contentType', 'content_dispo', - 'link_attributes', 'alias_visible', 'hide_from_tree', 'show_in_search', + 'link_attributes', 'alias_visible', 'hide_from_tree', ]; + /** Check the manager ACL and report the supplied fields and TVs that changed on commit. */ public function handle(Request $request): ResponseFactory { $validated = $request->validate([ 'id' => ['required', 'integer', 'min:1'], 'fields' => ['nullable', 'array'], + 'fields.published' => ['sometimes', 'required', 'boolean'], + 'fields.pub_date' => ['sometimes', 'required', 'integer', 'min:0'], + 'fields.unpub_date' => ['sometimes', 'required', 'integer', 'min:0'], 'tvs' => ['nullable', 'array'], ]); $id = (int)$validated['id']; - $fields = $this->pickFields((array)($validated['fields'] ?? []), self::WRITABLE_FIELDS); + $fields = $this->pickFields((array)$request->get('fields', []), self::WRITABLE_FIELDS); $tvs = (array)($validated['tvs'] ?? []); if ($fields === [] && $tvs === []) { @@ -44,33 +52,30 @@ public function handle(Request $request): ResponseFactory } $this->requirePermission('save_document'); - $document = $this->findDocument($id); - $this->requireDocumentAccess($id); - $this->requireUnlocked(7, $id); - - if (isset($fields['parent']) && (int)$fields['parent'] !== (int)$document->parent) { - $this->requireDocumentAccess(0, (int)$fields['parent']); - } - - // DocumentEdit works on a full record (it reads published/pub_date/parent unconditionally), - // so a partial update is completed from the stored row. - $current = []; - foreach (['pagetitle', 'alias', 'template', 'parent', 'published', 'pub_date', 'unpub_date', 'isfolder', 'hidemenu', 'menuindex'] as $column) { - $current[$column] = $document->getAttribute($column); - } - - $data = ['id' => $id] + $fields + $current + $this->tvValues($tvs); - try { - DocumentManager::edit($data); + $result = DocumentManager::editPatch($id, $fields, $this->tvValues($tvs), function (SiteContent $document) use ($id, $fields): void { + $this->requireDocumentAccess($id); + $this->requireUnlocked(7, $id); + if (isset($fields['parent']) && (int)$fields['parent'] !== (int)$document->parent) { + $this->requireDocumentAccess(0, (int)$fields['parent']); + } + }); + } catch (ModelNotFoundException) { + throw ValidationException::withMessages(['id' => "Document [{$id}] not found."]); } catch (ServiceValidationException $e) { throw ValidationException::withMessages($this->flatten($e->getValidationErrors())); } catch (ServiceActionException $e) { throw ValidationException::withMessages(['document' => $e->getMessage()]); } - $fresh = $this->findDocument($id); - $this->logManagerAction(5, 'Saved resource via MCP', $id, (string)$fresh->pagetitle); + $fresh = $result['document']; + $connection = $fresh->getConnection(); + $log = fn() => $this->logManagerAction(5, 'Saved resource via MCP', $id, (string)$fresh->pagetitle); + if ($connection->transactionLevel() > 0) { + $connection->afterCommit($log); + } else { + $log(); + } return $this->respondItem([ 'id' => $id, @@ -78,13 +83,13 @@ public function handle(Request $request): ResponseFactory 'alias' => $fresh->alias, 'published' => (bool)$fresh->published, 'editedon' => $fresh->editedon, - 'updated_fields' => array_keys($fields), - 'updated_tvs' => array_keys($tvs), + 'updated_fields' => $result['updated_fields'], + 'updated_tvs' => $result['updated_tvs'], ]); } /** - * DocumentManager reads TV values from the data array by TV name. + * Normalize TV values without merging their names into the document columns. * * @param array $tvs * @return array @@ -100,7 +105,13 @@ private function tvValues(array $tvs): array if (in_array($name, self::WRITABLE_FIELDS, true) || $name === 'id') { throw ValidationException::withMessages(['tvs' => "TV name [{$name}] collides with a document field."]); } - $values[$name] = is_array($value) ? implode('||', array_map('strval', $value)) : (string)$value; + $parts = is_array($value) ? $value : [$value]; + foreach ($parts as $part) { + if (!is_scalar($part) && $part !== null) { + throw ValidationException::withMessages(['tvs' => "TV [{$name}] expects scalar values."]); + } + } + $values[$name] = is_array($value) ? implode('||', array_map('strval', $parts)) : (string)$value; } return $values; @@ -126,9 +137,34 @@ private function flatten(array $errors): array public function schema(JsonSchema $schema): array { return [ - 'id' => $schema->integer()->min(1)->required(), - 'fields' => $schema->object()->description('Document columns to change: ' . implode(', ', self::WRITABLE_FIELDS)), - 'tvs' => $schema->object()->description('Template variable values keyed by TV name'), + 'id' => $schema->integer()->min(1)->required()->description('ID of the existing document to edit.'), + 'fields' => $schema->object([ + 'published' => $schema->union(['boolean', 'integer'])->enum([true, false, 0, 1])->description('Publication state. Changing it requires publish_document.'), + 'pub_date' => $schema->integer()->min(0)->description('Scheduled publication timestamp. Use 0 to clear.'), + 'unpub_date' => $schema->integer()->min(0)->description('Scheduled unpublication timestamp. Use 0 to clear.'), + ])->nullable()->description('Document columns to change. Provide fields, TVs or both. Allowed: ' . implode(', ', self::WRITABLE_FIELDS)), + 'tvs' => $schema->object()->nullable()->description('TV values keyed by names assigned to the final template. A list value is stored using the || separator.'), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::item($schema, [ + 'id' => $schema->integer()->required(), + 'pagetitle' => $schema->string()->required(), + 'alias' => $schema->string()->nullable()->required(), + 'published' => $schema->boolean()->required(), + 'editedon' => $schema->integer()->required(), + 'updated_fields' => $schema->array()->items($schema->string())->required() + ->description('Requested document fields whose stored values changed.'), + 'updated_tvs' => $schema->array()->items($schema->string())->required() + ->description('Requested TVs whose stored values were added or changed.'), + ], nullable: false); + } } diff --git a/src/Tools/Write/ElementsSaveTool.php b/src/Tools/Write/ElementsSaveTool.php index 3cc153f..c65a5c2 100644 --- a/src/Tools/Write/ElementsSaveTool.php +++ b/src/Tools/Write/ElementsSaveTool.php @@ -4,6 +4,8 @@ namespace EvolutionCMS\eMCP\Tools\Write; +use EvolutionCMS\eMCP\Support\ToolContract; + use EvolutionCMS\eMCP\Support\ElementTypes; use EvolutionCMS\eMCP\Tools\Elements\ElementsGetTool; use Illuminate\Contracts\JsonSchema\JsonSchema; @@ -16,6 +18,7 @@ #[Name('evo.write.elements.save')] #[Description('Create or update a template, TV, chunk, snippet or plugin. Requires new_*/save_* permission for the type; fires the same OnBefore*FormSave/On*FormSave events as the manager.')] +/** Create or update one CMS element using its manager permissions and events. */ class ElementsSaveTool extends BaseWriteTool { /** @var array manager_log action ids per element type */ @@ -106,9 +109,28 @@ public function handle(Request $request): ResponseFactory public function schema(JsonSchema $schema): array { return [ - 'type' => $schema->string()->enum(ElementTypes::names())->required(), - 'id' => $schema->integer()->min(1)->description('Omit to create a new element'), - 'fields' => $schema->object()->required()->description('Columns to write; code lives in content (template), default_text (tv), snippet (chunk/snippet) or plugincode (plugin)'), + 'type' => $schema->string()->enum(ElementTypes::names())->required() + ->description('Element type; determines the writable fields and the new or save permission.'), + 'id' => $schema->integer()->min(1)->nullable()->description('ID of an existing element. Omit to create one.'), + 'fields' => $schema->object()->required() + ->description('Writable columns for the type. Source fields: template content, TV default_text, chunk/snippet snippet, plugin plugincode. Backend code also requires code tools to be enabled and authorized.'), ]; } + + /** + * Advertise the structured envelope required by an MCP client. + * + * @return array + * @since 0.3.0 + */ + public function outputSchema(JsonSchema $schema): array + { + return ToolContract::item($schema, [ + 'id' => $schema->integer()->required(), + 'type' => $schema->string()->enum(ElementTypes::names())->required(), + 'name' => $schema->string()->required(), + 'mode' => $schema->string()->enum(['created', 'updated'])->required(), + 'updated_fields' => $schema->array()->items($schema->string())->required(), + ], nullable: false); + } } diff --git a/tests/Feature/StreamingAndResultLimitsBehaviorTest.php b/tests/Feature/StreamingAndResultLimitsBehaviorTest.php index a17ab01..513bbad 100644 --- a/tests/Feature/StreamingAndResultLimitsBehaviorTest.php +++ b/tests/Feature/StreamingAndResultLimitsBehaviorTest.php @@ -322,6 +322,7 @@ function data_get(array $target, string $key, mixed $default = null): mixed } } + require_once __DIR__ . '/../../src/Support/ToolContract.php'; require_once __DIR__ . '/../../src/Support/TraceContext.php'; require_once __DIR__ . '/../../src/Support/TransportError.php'; require_once __DIR__ . '/../../src/Support/JsonRpcPayload.php'; @@ -337,7 +338,6 @@ function data_get(array $target, string $key, mixed $default = null): mixed 'app.debug' => false, 'cms.settings.eMCP.trace.header' => 'X-Trace-Id', 'cms.settings.eMCP.trace.generate_if_missing' => true, - 'cms.settings.eMCP.toolset_version' => '1.0', 'cms.settings.eMCP.limits.max_payload_kb' => 256, 'cms.settings.eMCP.limits.max_result_bytes' => 32, 'cms.settings.eMCP.stream.enabled' => false, @@ -394,7 +394,7 @@ function data_get(array $target, string $key, mixed $default = null): mixed assertTrue($initializeResponseOk->getStatusCode() === 200, 'initialize should pass when result size is within limits'); $initBodyOk = json_decode($initializeResponseOk->getContent(), true); assertTrue(($initBodyOk['result']['serverInfo']['platform'] ?? null) === 'eMCP', 'initialize should inject platform metadata'); - assertTrue(($initBodyOk['result']['capabilities']['evo']['toolsetVersion'] ?? null) === '1.0', 'initialize should inject toolsetVersion'); + assertTrue(($initBodyOk['result']['capabilities']['evo']['toolsetVersion'] ?? null) === '2.0', 'initialize should inject toolsetVersion'); assertTrue( ($initBodyOk['result']['serverInfo']['site'] ?? null) === [ 'host' => null, diff --git a/tests/Fixtures/golden/evo_content_get.json b/tests/Fixtures/golden/evo_content_get.json index fde857d..def5f05 100644 --- a/tests/Fixtures/golden/evo_content_get.json +++ b/tests/Fixtures/golden/evo_content_get.json @@ -6,6 +6,6 @@ "deleted": 0 }, "meta": { - "toolsetVersion": "1.0" + "toolsetVersion": "2.0" } } diff --git a/tests/Fixtures/golden/evo_content_search.json b/tests/Fixtures/golden/evo_content_search.json index 93422be..9468516 100644 --- a/tests/Fixtures/golden/evo_content_search.json +++ b/tests/Fixtures/golden/evo_content_search.json @@ -4,6 +4,6 @@ "limit": 20, "offset": 0, "count": 0, - "toolsetVersion": "1.0" + "toolsetVersion": "2.0" } } diff --git a/tests/Fixtures/golden/initialize.json b/tests/Fixtures/golden/initialize.json index 1fe68e0..7717a3a 100644 --- a/tests/Fixtures/golden/initialize.json +++ b/tests/Fixtures/golden/initialize.json @@ -5,13 +5,13 @@ "protocolVersion": "2025-11-25", "serverInfo": { "name": "eMCP Content Server", - "version": "1.0.0", + "version": "2.0.0", "platform": "eMCP", "platformVersion": "dev" }, "capabilities": { "evo": { - "toolsetVersion": "1.0" + "toolsetVersion": "2.0" } } } diff --git a/tests/Fixtures/golden/tools_list.json b/tests/Fixtures/golden/tools_list.json index e356c28..ac2ec69 100644 --- a/tests/Fixtures/golden/tools_list.json +++ b/tests/Fixtures/golden/tools_list.json @@ -3,15 +3,48 @@ "id": "tools-1", "result": { "tools": [ - { "name": "evo.content.search" }, - { "name": "evo.content.get" }, - { "name": "evo.content.root_tree" }, - { "name": "evo.content.descendants" }, - { "name": "evo.content.ancestors" }, - { "name": "evo.content.children" }, - { "name": "evo.content.siblings" }, - { "name": "evo.model.list" }, - { "name": "evo.model.get" } + { + "name": "evo.content.search" + }, + { + "name": "evo.content.get" + }, + { + "name": "evo.content.tree" + }, + { + "name": "evo.content.ancestors" + }, + { + "name": "evo.content.siblings" + }, + { + "name": "evo.model.list" + }, + { + "name": "evo.model.get" + }, + { + "name": "evo.elements.list" + }, + { + "name": "evo.elements.get" + }, + { + "name": "evo.write.content.update" + }, + { + "name": "evo.write.content.create" + }, + { + "name": "evo.write.content.publish" + }, + { + "name": "evo.write.elements.save" + }, + { + "name": "evo.write.cache.clear" + } ] } } diff --git a/tests/Integration/ClosureTableInvariantsHttpTest.php b/tests/Integration/ClosureTableInvariantsHttpTest.php index a4d7c36..2b09208 100644 --- a/tests/Integration/ClosureTableInvariantsHttpTest.php +++ b/tests/Integration/ClosureTableInvariantsHttpTest.php @@ -156,17 +156,17 @@ function decodeJson(string $body, string $context): array 'id' => 'closure-root', 'method' => 'tools/call', 'params' => [ - 'name' => 'evo.content.root_tree', - 'arguments' => ['depth' => 4, 'limit' => 50, 'offset' => 0], + 'name' => 'evo.content.tree', + 'arguments' => ['id' => 0, 'depth' => 4, 'limit' => 50, 'offset' => 0], ], ], $headers); if ($rootResp['status'] !== 200) { - fail('root_tree expected 200, got ' . $rootResp['status']); + fail('tree from root expected 200, got ' . $rootResp['status']); } -$rootJson = decodeJson($rootResp['body'], 'root_tree'); +$rootJson = decodeJson($rootResp['body'], 'tree from root'); if (isset($rootJson['error'])) { - fail('root_tree returned JSON-RPC error'); + fail('tree from root returned JSON-RPC error'); } $items = $rootJson['result']['structuredContent']['items'] ?? null; @@ -184,11 +184,11 @@ function decodeJson(string $body, string $context): array $id = (int)($item['id'] ?? 0); if ($id < 1) { - fail('root_tree item has invalid id'); + fail('tree from root item has invalid id'); } if (isset($byId[$id])) { - fail('root_tree returned duplicate id ' . $id); + fail('tree from root returned duplicate id ' . $id); } $parent = (int)($item['parent'] ?? 0); @@ -216,7 +216,7 @@ function decodeJson(string $body, string $context): array 'method' => 'tools/call', 'params' => [ 'name' => 'evo.content.ancestors', - 'arguments' => ['id' => $candidateId, 'depth' => 10, 'limit' => 50, 'offset' => 0], + 'arguments' => ['id' => $candidateId], ], ], $headers); if ($ancResp['status'] !== 200) { @@ -253,7 +253,7 @@ function decodeJson(string $body, string $context): array 'id' => 'closure-children', 'method' => 'tools/call', 'params' => [ - 'name' => 'evo.content.children', + 'name' => 'evo.content.tree', 'arguments' => ['id' => $parentId, 'limit' => 100, 'offset' => 0], ], ], $headers); @@ -290,15 +290,15 @@ function decodeJson(string $body, string $context): array } if ($ancestorIds !== []) { - $topAncestorId = (int)array_key_last($ancestorIds); + $topAncestorId = (int)array_key_first($ancestorIds); $descResp = postJson($url, [ 'jsonrpc' => '2.0', 'id' => 'closure-desc', 'method' => 'tools/call', 'params' => [ - 'name' => 'evo.content.descendants', - 'arguments' => ['id' => $topAncestorId, 'depth' => 10, 'limit' => 200, 'offset' => 0], + 'name' => 'evo.content.tree', + 'arguments' => ['id' => $topAncestorId, 'depth' => 3, 'limit' => 100, 'offset' => 0], ], ], $headers); if ($descResp['status'] !== 200) { diff --git a/tests/Integration/RuntimeIntegrationHttpTest.php b/tests/Integration/RuntimeIntegrationHttpTest.php index 94d529a..3f1d54d 100644 --- a/tests/Integration/RuntimeIntegrationHttpTest.php +++ b/tests/Integration/RuntimeIntegrationHttpTest.php @@ -488,26 +488,11 @@ function runShellCommand(string $command, string $cwd = ''): array } $advancedCalls = [ - [ - 'name' => 'evo.content.neighbors', - 'arguments' => ['id' => 1, 'limit' => 2, 'offset' => 0], - ], - [ - 'name' => 'evo.content.prev_siblings', - 'arguments' => ['id' => 1, 'limit' => 2, 'offset' => 0], - ], - [ - 'name' => 'evo.content.next_siblings', - 'arguments' => ['id' => 1, 'limit' => 2, 'offset' => 0], - ], - [ - 'name' => 'evo.content.children_range', - 'arguments' => ['id' => 1, 'from' => 0, 'to' => 5, 'limit' => 2, 'offset' => 0], - ], - [ - 'name' => 'evo.content.siblings_range', - 'arguments' => ['id' => 1, 'from' => 0, 'to' => 5, 'limit' => 2, 'offset' => 0], - ], + ['name' => 'evo.content.siblings', 'arguments' => ['id' => 1, 'direction' => 'adjacent']], + ['name' => 'evo.content.siblings', 'arguments' => ['id' => 1, 'direction' => 'before', 'limit' => 2]], + ['name' => 'evo.content.siblings', 'arguments' => ['id' => 1, 'direction' => 'after', 'limit' => 2]], + ['name' => 'evo.content.tree', 'arguments' => ['id' => 1, 'menuindex_from' => 0, 'menuindex_to' => 5, 'limit' => 2]], + ['name' => 'evo.content.siblings', 'arguments' => ['id' => 1, 'menuindex_from' => 0, 'menuindex_to' => 5, 'limit' => 2]], ]; foreach ($advancedCalls as $advancedCall) { @@ -551,11 +536,11 @@ function runShellCommand(string $command, string $cwd = ''): array 'id' => 'invalid-range-1', 'method' => 'tools/call', 'params' => [ - 'name' => 'evo.content.children_range', + 'name' => 'evo.content.tree', 'arguments' => [ 'id' => 1, - 'from' => 5, - 'to' => 2, + 'menuindex_from' => 5, + 'menuindex_to' => 2, 'limit' => 1, 'offset' => 0, ], @@ -588,7 +573,7 @@ function runShellCommand(string $command, string $cwd = ''): array } $message = strtolower(trim((string)($firstBlock['text'] ?? ''))); - if ($message === '' || !str_contains($message, 'greater than or equal to from')) { + if ($message === '' || !str_contains($message, 'greater than or equal to menuindex_from')) { fail("{$label} invalid range isError response missing expected validation message."); } } diff --git a/tests/Integration/ToolsetV2SqliteHttpTest.php b/tests/Integration/ToolsetV2SqliteHttpTest.php new file mode 100644 index 0000000..2d6ed5b --- /dev/null +++ b/tests/Integration/ToolsetV2SqliteHttpTest.php @@ -0,0 +1,298 @@ + PDO::ERRMODE_EXCEPTION]); + +/** Run a bound statement on the fixture database. */ +function run(PDO $db, string $sql, array $parameters = []): PDOStatement +{ + $statement = $db->prepare($sql); + $statement->execute($parameters); + + return $statement; +} + +/** Fail with the name of the missing behavior. */ +function check(bool $pass, string $message): void +{ + if (!$pass) { + throw new RuntimeException($message); + } +} + +/** Send one actual JSON-RPC request to the local eMCP PAT endpoint. */ +function rpc(string $url, string $token, string $method, array|object $params): object +{ + $context = stream_context_create(['http' => [ + 'method' => 'POST', + 'header' => [ + 'Content-Type: application/json', + 'Accept: application/json, text/event-stream', + 'MCP-Protocol-Version: 2025-11-25', + 'Authorization: Bearer ' . $token, + ], + 'content' => json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => $method, 'params' => $params], JSON_THROW_ON_ERROR), + 'ignore_errors' => true, + 'timeout' => 10, + ]]); + $body = file_get_contents($url, false, $context); + + return json_decode($body, false, flags: JSON_THROW_ON_ERROR); +} + +/** Call a tool, optionally expecting an error, and validate every success against discovery. */ +function call(string $url, string $token, array $tools, string $name, array $arguments, ?string $error = null): ?object +{ + $response = rpc($url, $token, 'tools/call', ['name' => $name, 'arguments' => (object)$arguments]); + if ($error !== null) { + $errorEnvelope = isset($response->error) || ($response->result->isError ?? false); + check($errorEnvelope && ($error === '*' || str_contains(json_encode($response, JSON_THROW_ON_ERROR), $error)), + "{$name}: expected error {$error}, received " . json_encode($response, JSON_THROW_ON_ERROR)); + + return null; + } + + $result = $response->result->structuredContent ?? null; + check(is_object($result) && !($response->result->isError ?? false), + "{$name}: missing success result: " . json_encode($response, JSON_THROW_ON_ERROR)); + $validator = new Validator(); + $validator->validate($result, $tools[$name]->outputSchema); + check($validator->isValid(), "{$name}: outputSchema rejected its actual response: " . json_encode($validator->getErrors())); + + return $result; +} + +/** Check the complete ordered ID sequence of a page or path. */ +function ids(object $result, array $expected, string $case): void +{ + $actual = array_map(static fn(object $item): int => (int)$item->id, $result->items); + check($actual === $expected && $result->meta->count === count($expected), + "{$case}: expected " . json_encode($expected) . ', got ' . json_encode($actual)); +} + +$init = rpc($url, $admin, 'initialize', [ + 'protocolVersion' => '2025-11-25', + 'capabilities' => (object)[], + 'clientInfo' => ['name' => 'toolset-v2-integration', 'version' => '1.0'], +]); +$contract = governance_parse_toolset(dirname(__DIR__, 2) . '/TOOLSET.md'); +check(($init->result->capabilities->evo->toolsetVersion ?? null) === $contract['toolset_version'], 'initialize toolset version'); +$tools = []; +$cursor = null; +do { + $params = $cursor === null ? (object)[] : ['cursor' => $cursor]; + $page = rpc($url, $admin, 'tools/list', $params)->result ?? throw new RuntimeException('tools/list failed'); + foreach ($page->tools as $entry) { + check(!isset($tools[$entry->name]), "Duplicate tool name: {$entry->name}"); + $tools[$entry->name] = $entry; + } + $cursor = $page->nextCursor ?? null; +} while ($cursor !== null); +$coreTools = array_filter(array_keys($tools), static fn($name) => str_starts_with($name, 'evo.')); +check(count($coreTools) === 14 && array_diff($contract['canonical_tools'], $coreTools) === [], 'Exact canonical 14 tools'); +foreach ($coreTools as $name) { + $tool = $tools[$name]; + $properties = (array)$tool->inputSchema->properties; + foreach ($properties as $key => $property) { + check(trim($property->description ?? '') !== '', "{$name}: missing description of {$key}"); + } + foreach ($tool->inputSchema->required ?? [] as $key) { + check(isset($properties[$key]), "{$name}: unknown required parameter {$key}"); + } + check(($tool->outputSchema->type ?? null) === 'object', "{$name}: missing outputSchema"); + check(($tool->annotations->readOnlyHint ?? null) === !str_starts_with($name, 'evo.write.'), "{$name}: readOnlyHint mismatch"); +} +check(in_array('limit', $tools['evo.content.search']->inputSchema->required, true), 'search advertises required limit'); + +$base = (int)$db->query('SELECT MAX(id) FROM evo_site_content')->fetchColumn() + 100; +[$root, $other, $before, $anchor, $tie, $after, $grandchild, $private, $hiddenChild, $trashed, $siteStart] = + range($base, $base + 10); +$nodes = [ + [$root, 0, 60, 'Fixture root', 1, 0], + [$other, 0, 70, 'Other branch', 1, 0], + [$before, $root, 1, 'Before gap', 1, 0], + [$anchor, $root, 5, 'Original title', 1, 0], + [$tie, $root, 5, 'Equal position', 1, 0], + [$after, $root, 12, 'After gap', 1, 0], + [$grandchild, $anchor, 0, 'Grandchild', 1, 0], + [$private, $root, 30, 'Unpublished anchor', 0, 0], + [$hiddenChild, $private, 0, 'Visible child under hidden anchor', 1, 0], + [$trashed, $root, 40, 'Trashed anchor', 1, 1], + [$siteStart, $other, 0, 'Unrelated public document', 1, 0], +]; +$parents = []; +$template = (int)$db->query('SELECT MIN(id) FROM evo_site_templates')->fetchColumn(); +foreach ($nodes as [$id, $parent, $position, $title, $published, $deleted]) { + run($db, 'INSERT INTO evo_site_content (id,parent,menuindex,pagetitle,alias,template,published,deleted,isfolder) VALUES (?,?,?,?,?,?,?,?,1)', + [$id, $parent, $position, $title, 'emcp-fixture-' . $id, $template, $published, $deleted]); + $parents[$id] = $parent; + $ancestor = $id; + for ($depth = 0; $ancestor !== 0; $depth++) { + run($db, 'INSERT INTO evo_site_content_closure (ancestor,descendant,depth) VALUES (?,?,?)', [$ancestor, $id, $depth]); + $ancestor = $parents[$ancestor]; + } +} + +$read = static fn(string $name, array $args): object => call($url, $admin, $tools, 'evo.content.' . $name, $args); +$rootIds = array_map('intval', $db->query('SELECT id FROM evo_site_content WHERE parent = 0 AND deleted = 0 ORDER BY menuindex, id')->fetchAll(PDO::FETCH_COLUMN)); +ids($read('tree', ['id' => 0, 'limit' => 50]), $rootIds, 'tree default depth 1 from site root'); +$rootTree = $read('tree', ['id' => 0, 'depth' => 2, 'limit' => 50]); +$rootTreeIds = array_map(static fn($item) => (int)$item->id, $rootTree->items); +check(in_array($anchor, $rootTreeIds, true) && !in_array($grandchild, $rootTreeIds, true), 'root_tree(1) migrates to tree(0, 2)'); +check(count($rootTreeIds) === count(array_unique($rootTreeIds)), 'Root tree returned duplicate IDs'); +ids($read('tree', ['id' => $root, 'limit' => 50]), [$before, $anchor, $tie, $after, $private], 'children and default descendants migration'); +ids($read('tree', ['id' => $root, 'depth' => 2, 'limit' => 50]), + [$before, $anchor, $tie, $after, $private, $grandchild, $hiddenChild], 'descendants depth migration'); +ids($read('tree', ['id' => $root, 'depth' => 1, 'menuindex_from' => 5, 'menuindex_to' => 5, 'limit' => 50]), [$anchor, $tie], 'children_range migration'); +ids($read('siblings', ['id' => $anchor, 'limit' => 50]), [$before, $tie, $after, $private], 'siblings migration'); +ids($read('siblings', ['id' => $anchor, 'direction' => 'before', 'limit' => 50]), [$before], 'prev_siblings migration'); +ids($read('siblings', ['id' => $anchor, 'direction' => 'after', 'limit' => 50]), [$tie, $after, $private], 'next_siblings migration and tie'); +ids($read('siblings', ['id' => $anchor, 'direction' => 'adjacent']), [$before, $tie], 'neighbors migration across a gap and a tie'); +ids($read('siblings', ['id' => $anchor, 'menuindex_from' => 5, 'menuindex_to' => 5, 'limit' => 50]), [$tie], 'siblings_range migration'); +ids($read('ancestors', ['id' => $grandchild]), [$root, $anchor], 'ancestors migration without paging'); +check($read('ancestors', ['id' => $grandchild])->meta->truncated === false, 'Path should not be truncated'); + +$pathLimit = $read('ancestors', ['id' => $grandchild])->meta->limit; +$chainStart = $base + 20; +$chainEnd = $chainStart + $pathLimit; +$db->beginTransaction(); +try { + for ($id = $chainStart; $id <= $chainEnd; $id++) { + run($db, 'INSERT INTO evo_site_content (id,parent,menuindex,pagetitle,alias,template,published,deleted,isfolder) VALUES (?,?,0,?,?,?,1,0,1)', + [$id, $id === $chainStart ? $root : $id - 1, 'Deep path fixture', 'emcp-fixture-' . $id, $template]); + run($db, 'INSERT INTO evo_site_content_closure (ancestor,descendant,depth) VALUES (?,?,?)', + [$root, $id, $id - $chainStart + 1]); + for ($ancestor = $chainStart; $ancestor <= $id; $ancestor++) { + run($db, 'INSERT INTO evo_site_content_closure (ancestor,descendant,depth) VALUES (?,?,?)', [$ancestor, $id, $id - $ancestor]); + } + } + $db->commit(); +} catch (Throwable $e) { + $db->rollBack(); + throw $e; +} +$boundedPath = $read('ancestors', ['id' => $chainEnd]); +ids($boundedPath, range($chainStart, $chainEnd - 1), 'Server-limited path keeps the nearest ancestors'); +check($boundedPath->meta->truncated === true, 'Server-limited ancestor path reports truncation'); + +$role = (int)$db->query('SELECT MAX(id) FROM evo_user_roles')->fetchColumn() + 1; +$user = (int)$db->query('SELECT MAX(id) FROM evo_users')->fetchColumn() + 1; +$editor = 'emcp_' . bin2hex(random_bytes(20)); +run($db, 'INSERT INTO evo_user_roles (id,name) VALUES (?,?)', [$role, 'eMCP fixture ' . $role]); +run($db, 'INSERT INTO evo_users (id,username,password) VALUES (?,?,?)', [$user, 'emcp-fixture-' . $user, '']); +run($db, 'INSERT INTO evo_user_attributes (internalKey,role) VALUES (?,?)', [$user, $role]); +foreach (['emcp', 'save_document'] as $permission) { + run($db, 'INSERT INTO evo_role_permissions (role_id,permission) VALUES (?,?)', [$role, $permission]); +} +run($db, 'INSERT INTO evo_emcp_tokens (user_id,name,token_prefix,token_hash,scopes) VALUES (?,?,?,?,?)', [ + $user, 'test fixture', substr($editor, 0, 12), TokenService::hash($editor), '["mcp:read","mcp:call","mcp:write"]', +]); +try { + foreach ([$chainEnd + 99, $trashed, $private] as $missing) { + foreach (['all', 'before', 'after', 'adjacent'] as $direction) { + $args = ['id' => $missing, 'direction' => $direction] + ($direction === 'adjacent' ? [] : ['limit' => 50]); + ids(call($url, $editor, $tools, 'evo.content.siblings', $args), [], "Empty sibling {$direction} for unavailable anchor {$missing}"); + } + ids(call($url, $editor, $tools, 'evo.content.tree', ['id' => $missing, 'limit' => 50]), [], 'Empty tree for unavailable anchor'); + ids(call($url, $editor, $tools, 'evo.content.ancestors', ['id' => $missing]), [], 'Empty path for unavailable anchor'); + } + + $tvValues = []; + foreach (['one', 'two'] as $suffix) { + $name = 'emcp_' . $anchor . '_' . $suffix; + run($db, 'INSERT INTO evo_site_tmplvars (name,type) VALUES (?,?)', [$name, 'text']); + $tv = (int)$db->lastInsertId(); + run($db, 'INSERT INTO evo_site_tmplvar_templates (tmplvarid,templateid) VALUES (?,?)', [$tv, $template]); + run($db, 'INSERT INTO evo_site_tmplvar_contentvalues (tmplvarid,contentid,value) VALUES (?,?,?)', [$tv, $anchor, 'original']); + $tvValues[$name] = $tv; + } + [$tv1, $tv2] = array_values($tvValues); + [$name1, $name2] = array_keys($tvValues); + $write = static fn(array $fields, array $tvs, ?string $error = null): ?object => + call($url, $editor, $tools, 'evo.write.content.update', ['id' => $anchor, 'fields' => $fields, 'tvs' => $tvs], $error); + $row = static fn(): array => run($db, 'SELECT pagetitle,published,pub_date,unpub_date FROM evo_site_content WHERE id=?', [$anchor])->fetch(PDO::FETCH_ASSOC); + $tvRows = static fn(): array => run($db, 'SELECT value FROM evo_site_tmplvar_contentvalues WHERE contentid=? ORDER BY tmplvarid', [$anchor])->fetchAll(PDO::FETCH_COLUMN); + $original = $row(); + + foreach (['published' => false, 'pub_date' => time() + 3600, 'unpub_date' => time() + 7200] as $field => $value) { + $write([$field => $value, 'pagetitle' => 'Denied'], [$name1 => 'Denied'], 'publish_document'); + check($row() === $original && $tvRows() === ['original', 'original'], "Unauthorized {$field} left fields and TVs unchanged"); + } + $write(['pagetitle' => 'Unknown TV'], ['unassigned_tv' => 'value'], 'not assigned'); + check($row() === $original, 'Unknown TV failed before document write'); + + // Fail the second TV only when both the document and the first TV have already been changed. + $trigger = 'emcp_abort_tv_' . $anchor; + $db->exec("CREATE TRIGGER {$trigger} BEFORE UPDATE ON evo_site_tmplvar_contentvalues + WHEN NEW.tmplvarid = {$tv2} AND NEW.contentid = {$anchor} + AND (SELECT pagetitle FROM evo_site_content WHERE id = {$anchor}) = 'Rollback title' + AND (SELECT value FROM evo_site_tmplvar_contentvalues WHERE contentid = {$anchor} AND tmplvarid = {$tv1}) = 'written first' + BEGIN SELECT RAISE(ABORT, 'Second TV fixture failure'); END"); + try { + $write(['pagetitle' => 'Rollback title'], [$name1 => 'written first', $name2 => 'fails second'], '*'); + check($row() === $original && $tvRows() === ['original', 'original'], 'Second TV failure rolled back both the document and the first TV'); + } finally { + $db->exec("DROP TRIGGER {$trigger}"); + } + + $saved = $write(['pagetitle' => 'Saved title', 'published' => true], [$name1 => 'saved', $name2 => 'saved']); + check($saved->item->updated_fields === ['pagetitle'] && $saved->item->updated_tvs === [$name1, $name2], + 'Response reports the requested fields and TVs that changed'); + check($row()['pagetitle'] === 'Saved title' && $tvRows() === ['saved', 'saved'], 'Fields and TVs committed together'); + + run($db, 'INSERT INTO evo_role_permissions (role_id,permission) VALUES (?,?)', [$role, 'publish_document']); + $publishDate = time() + 86400; + $unpublishDate = $publishDate + 86400; + $write(['pub_date' => $publishDate, 'unpub_date' => $unpublishDate], []); + check((int)$row()['pub_date'] === $publishDate && (int)$row()['unpub_date'] === $unpublishDate, 'Publisher can change dates alone'); + $write(['published' => false, 'pub_date' => 0, 'unpub_date' => 0], []); + check((int)$row()['published'] === 0 && (int)$row()['pub_date'] === 0 && (int)$row()['unpub_date'] === 0, 'Publisher can unpublish and clear dates'); + + $startId = (int)$db->query("SELECT setting_value FROM evo_system_settings WHERE setting_name = 'site_start'")->fetchColumn(); + if ($startId > 0) { + call($url, $admin, $tools, 'evo.write.content.update', ['id' => $startId, 'fields' => ['published' => false]], 'cannot be unpublished'); + } + + // Exercise one successful call for each remaining tool, using only disposable CMS records. + $read('search', ['limit' => 5, 'parent' => $root, 'with_tvs' => [$name1]]); + check($read('get', ['id' => $chainEnd + 99])->item === null, 'content.get missing item output'); + call($url, $admin, $tools, 'evo.model.list', ['model' => 'SiteTemplate', 'limit' => 1]); + call($url, $admin, $tools, 'evo.model.get', ['model' => 'SiteTemplate', 'id' => $template]); + call($url, $admin, $tools, 'evo.elements.list', ['type' => 'template', 'limit' => 1]); + call($url, $admin, $tools, 'evo.elements.get', ['type' => 'template', 'id' => $template]); + $created = call($url, $admin, $tools, 'evo.write.content.create', ['parent' => $other, 'fields' => ['pagetitle' => 'Schema fixture ' . $anchor]]); + call($url, $admin, $tools, 'evo.write.content.publish', ['id' => $created->item->id, 'action' => 'publish']); + call($url, $admin, $tools, 'evo.write.elements.save', ['type' => 'chunk', 'fields' => ['name' => 'schema_chunk_' . $anchor, 'snippet' => 'Fixture']]); + call($url, $admin, $tools, 'evo.write.cache.clear', []); +} finally { + run($db, 'DELETE FROM evo_emcp_tokens WHERE user_id=?', [$user]); +} + +echo "Toolset v2 HTTP checks passed: 14 schemas, migration, visibility, rollback and publication permissions.\n"; diff --git a/tests/Phase25/ContractsAndPipelineTest.php b/tests/Phase25/ContractsAndPipelineTest.php index c16266f..4f2015b 100644 --- a/tests/Phase25/ContractsAndPipelineTest.php +++ b/tests/Phase25/ContractsAndPipelineTest.php @@ -67,16 +67,9 @@ function assertContains(string $haystack, string $needle, string $message): void $toolFiles = [ __DIR__ . '/../../src/Tools/Content/ContentSearchTool.php', __DIR__ . '/../../src/Tools/Content/ContentGetTool.php', - __DIR__ . '/../../src/Tools/Content/ContentRootTreeTool.php', - __DIR__ . '/../../src/Tools/Content/ContentDescendantsTool.php', + __DIR__ . '/../../src/Tools/Content/ContentTreeTool.php', __DIR__ . '/../../src/Tools/Content/ContentAncestorsTool.php', - __DIR__ . '/../../src/Tools/Content/ContentChildrenTool.php', __DIR__ . '/../../src/Tools/Content/ContentSiblingsTool.php', - __DIR__ . '/../../src/Tools/Content/ContentNeighborsTool.php', - __DIR__ . '/../../src/Tools/Content/ContentPrevSiblingsTool.php', - __DIR__ . '/../../src/Tools/Content/ContentNextSiblingsTool.php', - __DIR__ . '/../../src/Tools/Content/ContentChildrenRangeTool.php', - __DIR__ . '/../../src/Tools/Content/ContentSiblingsRangeTool.php', __DIR__ . '/../../src/Tools/ModelCatalog/ModelListTool.php', __DIR__ . '/../../src/Tools/ModelCatalog/ModelGetTool.php', ]; @@ -94,9 +87,6 @@ function assertContains(string $haystack, string $needle, string $message): void $requiredContractFiles = [ __DIR__ . '/../../src/Contracts/ToolArguments/ContentSearchArgs.php', __DIR__ . '/../../src/Contracts/ToolArguments/ContentGetArgs.php', - __DIR__ . '/../../src/Contracts/ToolArguments/ContentNodeListArgs.php', - __DIR__ . '/../../src/Contracts/ToolArguments/ContentNodeRangeArgs.php', - __DIR__ . '/../../src/Contracts/ToolArguments/ContentRootTreeArgs.php', __DIR__ . '/../../src/Contracts/ToolArguments/ModelListArgs.php', __DIR__ . '/../../src/Contracts/ToolArguments/ModelGetArgs.php', __DIR__ . '/../../src/Contracts/ToolResponses/ListToolResponse.php', diff --git a/tests/Phase6/AdvancedTreeToolsContractsTest.php b/tests/Phase6/AdvancedTreeToolsContractsTest.php index 617a8f9..9a646e9 100644 --- a/tests/Phase6/AdvancedTreeToolsContractsTest.php +++ b/tests/Phase6/AdvancedTreeToolsContractsTest.php @@ -16,64 +16,8 @@ function assertContainsText(string $haystack, string $needle, string $message): $root = dirname(__DIR__, 2); -/** @var array> $advancedTools */ -$advancedTools = [ - 'ContentNeighborsTool.php' => [ - 'name' => 'evo.content.neighbors', - 'scope' => 'neighborsOf', - ], - 'ContentPrevSiblingsTool.php' => [ - 'name' => 'evo.content.prev_siblings', - 'scope' => 'prevSiblingsOf', - ], - 'ContentNextSiblingsTool.php' => [ - 'name' => 'evo.content.next_siblings', - 'scope' => 'nextSiblingsOf', - ], - 'ContentChildrenRangeTool.php' => [ - 'name' => 'evo.content.children_range', - 'scope' => 'childrenRangeOf', - ], - 'ContentSiblingsRangeTool.php' => [ - 'name' => 'evo.content.siblings_range', - 'scope' => 'siblingsRangeOf', - ], -]; - -foreach ($advancedTools as $fileName => $meta) { - $path = $root . '/src/Tools/Content/' . $fileName; - assertTrue(is_file($path), "Missing advanced tool file: {$fileName}"); - - $content = file_get_contents($path); - assertTrue(is_string($content), "Unable to read advanced tool file: {$fileName}"); - - $toolName = $meta['name']; - assertTrue( - str_contains($content, "#[Name('{$toolName}')]") || str_contains($content, "#[Name(\"{$toolName}\")]"), - "Missing canonical #[Name] for {$toolName} in {$fileName}" - ); - assertContainsText($content, 'extends BaseContentTool', "{$fileName} must extend BaseContentTool"); - assertContainsText($content, $meta['scope'], "{$fileName} must use dedicated SiteContent scope"); - assertContainsText($content, 'resolveLimitOffset', "{$fileName} must enforce limit/offset guardrails"); - assertContainsText($content, 'normalizeWithTvs', "{$fileName} must normalize with_tvs payload"); - assertContainsText($content, 'respondList(', "{$fileName} must return list contract response"); +$contract = file_get_contents($root . '/TOOLSET.md'); +foreach (['root_tree', 'children', 'descendants', 'children_range', 'prev_siblings', 'next_siblings', 'neighbors', 'siblings_range', 'ancestors'] as $legacy) { + assertContainsText($contract, "| `{$legacy}(", "Missing v1 migration for {$legacy}"); } - -/** @var array $rangeTools */ -$rangeTools = [ - 'ContentChildrenRangeTool.php', - 'ContentSiblingsRangeTool.php', -]; - -foreach ($rangeTools as $fileName) { - $path = $root . '/src/Tools/Content/' . $fileName; - $content = file_get_contents($path); - assertTrue(is_string($content), "Unable to read {$fileName}"); - - assertContainsText($content, "'from' => ['required', 'integer', 'min:0']", "{$fileName} must require from"); - assertContainsText($content, "'to' => ['nullable', 'integer', 'min:0']", "{$fileName} must validate to"); - assertContainsText($content, 'to must be greater than or equal to from', "{$fileName} must reject invalid from/to"); -} - -echo "Advanced tree tool contract checks passed.\n"; - +echo "Advanced tree tool migration contract checks passed.\n"; diff --git a/tests/Phase6/SiteContentContractsTest.php b/tests/Phase6/SiteContentContractsTest.php index 287ede6..cf0154f 100644 --- a/tests/Phase6/SiteContentContractsTest.php +++ b/tests/Phase6/SiteContentContractsTest.php @@ -20,16 +20,9 @@ function assertContainsText(string $haystack, string $needle, string $message): $expectedTools = [ 'ContentSearchTool.php' => 'evo.content.search', 'ContentGetTool.php' => 'evo.content.get', - 'ContentRootTreeTool.php' => 'evo.content.root_tree', - 'ContentDescendantsTool.php' => 'evo.content.descendants', + 'ContentTreeTool.php' => 'evo.content.tree', 'ContentAncestorsTool.php' => 'evo.content.ancestors', - 'ContentChildrenTool.php' => 'evo.content.children', 'ContentSiblingsTool.php' => 'evo.content.siblings', - 'ContentNeighborsTool.php' => 'evo.content.neighbors', - 'ContentPrevSiblingsTool.php' => 'evo.content.prev_siblings', - 'ContentNextSiblingsTool.php' => 'evo.content.next_siblings', - 'ContentChildrenRangeTool.php' => 'evo.content.children_range', - 'ContentSiblingsRangeTool.php' => 'evo.content.siblings_range', ]; foreach ($expectedTools as $fileName => $toolName) { @@ -56,43 +49,11 @@ function assertContainsText(string $haystack, string $needle, string $message): assertContainsText($searchContent, 'resolveLimitOffset', 'search must enforce limit/offset guardrails'); assertContainsText($searchContent, 'resolveDepth', 'search must enforce depth guardrails'); -$treeTools = [ - 'ContentRootTreeTool.php', - 'ContentDescendantsTool.php', - 'ContentAncestorsTool.php', - 'ContentChildrenTool.php', - 'ContentSiblingsTool.php', - 'ContentNeighborsTool.php', - 'ContentPrevSiblingsTool.php', - 'ContentNextSiblingsTool.php', - 'ContentChildrenRangeTool.php', - 'ContentSiblingsRangeTool.php', -]; - -foreach ($treeTools as $fileName) { - $path = $root . '/src/Tools/Content/' . $fileName; - $content = file_get_contents($path); - assertTrue(is_string($content), "Unable to read {$fileName}"); - - assertContainsText($content, 'resolveLimitOffset', "{$fileName} must enforce limit/offset"); - assertContainsText($content, 'normalizeWithTvs', "{$fileName} must normalize with_tvs payload"); - assertContainsText($content, '->where(', "{$fileName} must apply explicit query filters"); - assertContainsText($content, 'respondList(', "{$fileName} must return list contract response"); -} - -$rangeTools = [ - 'ContentChildrenRangeTool.php', - 'ContentSiblingsRangeTool.php', -]; - -foreach ($rangeTools as $fileName) { - $path = $root . '/src/Tools/Content/' . $fileName; - $content = file_get_contents($path); - assertTrue(is_string($content), "Unable to read {$fileName}"); - - assertContainsText($content, "'from' => ['required', 'integer', 'min:0']", "{$fileName} must require from range bound"); - assertContainsText($content, "'to' => ['nullable', 'integer', 'min:0']", "{$fileName} must validate to range bound"); - assertContainsText($content, 'to must be greater than or equal to from', "{$fileName} must reject invalid ranges"); +foreach (['ContentTreeTool.php', 'ContentAncestorsTool.php', 'ContentSiblingsTool.php'] as $fileName) { + $source = file_get_contents($root . '/src/Tools/Content/' . $fileName); + assertContainsText($source, 'findAnchor', "{$fileName} must check anchor access"); + assertContainsText($source, 'tvSchema', "{$fileName} must advertise TV projection"); + assertContainsText($source, 'respondList(', "{$fileName} must return the list envelope"); } echo "SiteContent tree/TV contract checks passed.\n"; diff --git a/tests/Unit/ToolDefinitionsTest.php b/tests/Unit/ToolDefinitionsTest.php new file mode 100644 index 0000000..eb250f6 --- /dev/null +++ b/tests/Unit/ToolDefinitionsTest.php @@ -0,0 +1,75 @@ + 'number', + 'NULL' => 'null', + default => gettype($default), + }; + assertContract(in_array($actualType, $types, true) || ($actualType === 'integer' && in_array('number', $types, true)), + "{$path}: default has the wrong type"); + if (isset($schema['enum'])) { + assertContract(in_array($default, $schema['enum'], true), "{$path}: default is outside its enum"); + } + } + + foreach ($properties as $key => $property) { + if ($input) { + assertContract(trim($property['description'] ?? '') !== '', "{$path}.{$key}: parameter has no description"); + } + checkSchema($property, "{$path}.{$key}", $input); + } + if (isset($schema['items'])) { + checkSchema($schema['items'], $path . '[]', $input); + } +} + +$classes = (new ReflectionClass(ContentServer::class))->getDefaultProperties()['tools']; +$toolNames = []; +foreach ($classes as $class) { + $definition = (new $class())->toArray(); + $name = $definition['name']; + assertContract(!in_array($name, $toolNames, true), "Duplicate tool name {$name}"); + $toolNames[] = $name; + assertContract(trim($definition['description'] ?? '') !== '', "{$name}: no purpose description"); + assertContract(($definition['inputSchema']['type'] ?? null) === 'object', "{$name}: input schema must be an object"); + assertContract(($definition['outputSchema']['type'] ?? null) === 'object', "{$name}: missing structured output schema"); + checkSchema($definition['inputSchema'], $name . '.inputSchema', true); + checkSchema($definition['outputSchema'], $name . '.outputSchema', false); +} + +$contract = governance_parse_toolset($root . '/TOOLSET.md'); +assertContract($contract['toolset_version'] === ToolContract::VERSION, 'Documented version differs from runtime'); +assertContract(count($toolNames) === 14 && $contract['canonical_tools'] === $toolNames, + 'The registered Evo tools differ from the canonical toolset'); + +echo "All 14 Evo definitions serialize with documented input and output schemas.\n"; From d68ace4cad2f728c028dcdc366770560a2775d74 Mon Sep 17 00:00:00 2001 From: "middle:Sokil" Date: Wed, 18 Nov 2026 15:15:10 +0200 Subject: [PATCH 2/2] upd(emcp): document the published DocumentManager dependency --- TOOLSET.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TOOLSET.md b/TOOLSET.md index 6b27c8e..cbb5a70 100644 --- a/TOOLSET.md +++ b/TOOLSET.md @@ -184,7 +184,7 @@ Canonical mapping: ## Migration from toolset 1.0 -Deploy both packages together. Toolset 2.0 requires DocumentManager 1.1.0 for atomic document and TV updates. +Upgrade to [DocumentManager 1.1.0](https://github.com/evolution-cms/DocumentManager/releases/tag/1.1.0) or a later 1.x release before switching to Toolset 2.0. This release provides the atomic document and TV update API. Composer resolves the published dependency without a local path repository. The names below are relative to the `evo.content.` prefix. | v1 call | v2 call |