Appearance
MCP Connector
Flow ID: IN-24 | Module(s):
src/Mcp/(Advisable\Mcp\),src/Domains/Order/SalesAnalytics,src/Domains/Product/PriceTracking,ecommercen/settings,ecommercen/helpers,ecommercen/audit| Complexity: High Last Updated: 2026-11-13 — Known Issue 17'sBlogArticle.phpandArticleVisibilityScope.phpcitations follow pull request #352's docblock changes; previous: 2026-11-13 — rule 38 and Known Issue 17 describe the correctedCONTENT_INSTRUCTIONSandcreate_articleguidance (#903); three staleMcpServerFactory.phpmethod ranges re-anchored; previous: 2026-11-12 — Known Issue 20 fixed (pull request #349): the storefront author page now lists only published, already-dated articles, so a connector-created draft that names an author stays off it (Known Issues 17 and 20); previous: 2026-11-12 — the blog-model citations in rule 38 and Known Issue 18 follow pull request #351's line shifts; Known Issue 17'sblog_dateinput citation is re-anchored (McpServerFactory.php:696), and theAdv_blog.phpcitations in Known Issues 17, 18 and 20 follow the controller's 13-line shift (#898); previous: 2026-11-11 — #824 review follow-up: saving the switch clears the whole pscache (On/off switch, Cache timing), so OFF applies at once in every language; previous: 2026-11-11 — Known Issue 18 fixed (#900): on the standard storefront a published article with no category now opens, with no related articles and no previous/next links (rule 38, Known Issues 17-18); previous: 2026-11-06 — #1017 resync: barcode params onsearch_productsandbarcodesprojection (#1010); previous: 2026-11-04 — 4.129.0 resync: citations re-anchored; previous: 2026-10-19 — doc-drift fix: two create tools, not one (Business Context); what the full-row translation merge still does under the #857 upsert, the create tools'insertForEntity()path, and the merge's lost-update window (rule 2, Entity tables, Client Extension Points, Known Issue 19); on the standard storefront a connector-created article needs a category for its published page to render and ablog_dateto be listed, and a draft that names an author is listed on the author page (rule 38, Known Issues 17, 18 and 20, tracked as #896, #900 and #899); previous: 2026-10-02
Business Context
The MCP Connector is a per-eshop Model Context Protocol server that lets an eshop owner connect Claude (claude.ai, Claude Desktop, or Claude Code) and edit SEO and content — categories, products, and brand/vendor pages (names, descriptions, meta fields) — conversationally, view read-only sales analytics, and author blog articles (list/get/create/update, including publishing) under a separate content scope. MCP SEO Brief #2 (#362–#367, #371) added category bulk/stats parity with products — categories_stats, products_stats, categories_batch_get, categories_batch_update, server-side list_categories filters, and lightweight completeness metadata on both list outputs. Blog-article authoring (#714) added the connector's second create tool, create_article, next to the product-tag create_product_tag (#713); every other write tool only edits existing records (McpServerFactory.php:596-608, 682-700).
A token carries one or more of three scopes — seo (catalog/SEO surface: 20 read/write tools), analytics (7 read-only sales tools), and content (4 blog-authoring tools, Scopes.php:31-33); get_shop_info is registered under every scope (McpServerFactory.php:141-175). An seo-only token sees a 21-tool surface (get_shop_info + 20). An analytics-only token is structurally read-only — create() never registers a write tool for it (McpServerFactory.php:166-168, proven by ServerFactoryTest::test_analytics_only_scope_registers_no_write_tools). A content-only token sees a 5-tool surface (get_shop_info + the 4 blog tools). Instruction blocks are composed per active capability by buildInstructions() (McpServerFactory.php:183-197), and a token holding several scopes receives them concatenated — so no block may make a connector-wide create claim: SEO_INSTRUCTIONS scopes its "product tags only" statement to the catalog tools it describes (:37-61) and CONTENT_INSTRUCTIONS (:81-107) names create_product_tag as the other create tool. The surface has exactly two create tools — create_product_tag under seo (#713) and create_article under content (#714) — and no delete tool of any kind.
The connector is served at POST|GET|DELETE /mcp/c/<token> using the official mcp/sdk ~0.6.0 (composer.json:51) over Streamable HTTP (JSON-RPC). It is off by default: the on/off switch is the Advisable-only Registry setting MCP_CONNECTOR.ENABLED (a checkbox on settings/only_advisable; a missing row reads as off), read through isMcpConnectorEnabled() — it replaced the APP_MCP_CONNECTOR_ENABLED env var in #824. Authentication is a secret-URL bearer token stored as a sha256 hash; the admin panel (settings/mcp_connector) lists all active tokens and generates, rotates, and revokes each independently, choosing scopes per token (AdvMcpConnectorSettings.php:37-99).
The feature was shipped in 4.107.0 (epic #312, docs/changelog/Changelog.4.107.md:42-81) and received a multi-pod session-store fix in 4.108.0 (#337, docs/changelog/Changelog.4.108.md:10, 31). The read-only Sales & Analytics layer + token scopes shipped in 4.117.0 (epic #403, foundation #404-#407 / Phase-1 #408-#411 / Phase-2 #413-#415 / tests-docs #412), docs/changelog/Changelog.4.117.md:5-45. Blog-article authoring (epic #714 — four tools under a new content scope) shipped in 4.123.0 (docs/changelog/Changelog.4.123.md:173).
The on/off switch started life as the APP_MCP_CONNECTOR_ENABLED env var, which epic #312 deliberately kept out of the admin UI. #824 reversed that: the switch is now the Advisable-only registry setting MCP_CONNECTOR.ENABLED, a forward-only migration seeded each environment's row once from the env var's value, and the env var is retired (see the "On/off switch" subsection under Legacy Layer, and Known Issue 11).
API Reference
Protocol Surface
This is a JSON-RPC-over-Streamable-HTTP surface, distinct from the platform's JWT REST API in src/Rest/. It is not a src/Rest/ controller.
| Endpoint | Methods | Route (file:line) | Resolves to | Auth | Roles |
|---|---|---|---|---|---|
/mcp/c/<token> | POST, GET, DELETE | application/config/routes.php:825-827 | Mcp::connector($token) | secret-URL token (sha256-hashed; token IS the credential) | none |
settings/mcp_connector | GET | routes.php:190, 207 | Mcp_connector::index | session/admin | ADVISABLE, DEVELOPER, ADMIN |
settings/mcp_connector/generate | POST | routes.php:191, 208 (catch-all) | Mcp_connector::generate | session/admin + POST only | ADVISABLE, DEVELOPER, ADMIN |
settings/mcp_connector/rotate/{id} | POST | routes.php:191, 208 (catch-all) | Mcp_connector::rotate($id) | session/admin + POST only | ADVISABLE, DEVELOPER, ADMIN |
settings/mcp_connector/revoke/{id} | POST | routes.php:191, 208 (catch-all) | Mcp_connector::revoke($id) | session/admin + POST only | ADVISABLE, DEVELOPER, ADMIN |
The connector route regex [A-Za-z0-9_-]+ matches a 43-char base64url token and is placed before the storefront language catch-alls. There is no separate SDK route; the SDK transport is driven entirely inside McpRequestHandler::handle().
protocolVersion negotiation (#861). McpRequestHandler::requestedProtocolVersion() peeks at the request body; only when the JSON-RPC method is initialize and params.protocolVersion is a string does it map it with ProtocolVersion::tryFrom() (anything else yields null), rewinds or rebuilds the body so the SDK can still read it, and passes the result to McpServerFactory::create($scopes, ?ProtocolVersion $protocolVersion = null), which calls setProtocolVersion() when non-null. The server therefore echoes a supported requested version (2024-11-05, 2025-03-26, 2025-06-18, 2025-11-25) and otherwise answers with the SDK latest (2025-11-25), per the MCP lifecycle version-negotiation rule. The SDK transport middleware (CORS, DNS-rebinding, protocol-version header check) stays disabled via middleware: [].
JSON-RPC methods spoken by the connector: initialize, notifications/initialized, tools/list, tools/call. The smoke harness (tests/smoke/mcp/README.md:21-27) proves the initialize → notifications/initialized → tools/list cross-process round-trip; the full tools/call exercise is covered by the curl collection in docs/guides/mcp-connector.md. Error codes: 401 → -32001, 429 → -32029, 500 → -32603 (McpRequestHandler.php:116-120).
The MCP Tools (32 total: 21 SEO + 7 analytics + 4 content, counted from addTool( calls in McpServerFactory.php)
SEO/Catalog Tools (21)
| SDK tool name | Handler method | Domain service called | Scope | Write? |
|---|---|---|---|---|
get_shop_info | ShopTools::getShopInfo | Registry (site title) + LanguageResolver | all | read |
list_categories | CategoryTools::listCategories | Category\Service::all (filters: search, has_meta, has_meta_title, has_meta_description, has_description, has_complete_description, parent_id, is_active→published; per_page max 200; default returns ALL; rows carry lightweight completeness metadata) | seo | read |
get_category | CategoryTools::getCategory | Category\Service::get | seo | read |
update_category | CategoryTools::updateCategory | Category\WriteService::update | seo | write |
categories_batch_get | CategoryTools::categoriesBatchGet | Category\Service::all (WHERE IN on id; max 100, ordered + missing) | seo | read |
categories_batch_update | CategoryTools::categoriesBatchUpdate | Category\WriteService::update (per row; max 50, best-effort; data + results + missing) | seo | write |
categories_stats | CategoryTools::categoriesStats | Category\Service::stats (one aggregate query; scope parent_id, is_active) | seo | read |
search_products | ProductTools::searchProducts | Product\Service::all (filters: query, category_id, brand_id/vendor_id alias, has_meta, has_complete_description, is_active, include_inactive, updated_since, barcode with barcode_match exact (default, an IN match that can use KEY barcode) or partial (LIKE scan); any other barcode_match throws; per_page max 200; defaults to active + non-deleted, which also applies to barcode lookups; rows carry lightweight completeness metadata and barcodes [{barcode, product_code}]) | seo | read |
products_stats | ProductTools::productsStats | Product\Service::stats (one aggregate query; scope category_id, brand_id, is_active) | seo | read |
get_product | ProductTools::getProduct | Product\Service::get (returns text/meta/vendor/categories/tags — tags added by #713, ProductTools.php:507; barcodes as [{barcode, product_code}], ProductTools.php:508 — plus read-only price, is_active, updated_at, stock summed over active SKUs) | seo | read |
update_product | ProductTools::updateProduct | Product\WriteService::update (+ Vendor\Service::get for brand validation; since #713 also takes tag_ids, a full-replacement set synced via TagPivotWriteRepository::syncForProduct()) | seo | write |
update_product_content | ProductTools::updateProductContent | Product\WriteService::update | seo | write |
products_batch_get | ProductTools::productsBatchGet | Product\Service::all (WHERE IN on id; each row goes through view(), so it also carries barcodes, ProductTools.php:508) | seo | read |
products_batch_update | ProductTools::productsBatchUpdate | Product\WriteService::update (per row) | seo | write |
list_product_tags | TagTools::listProductTags | Tag\Tag\Service::all (filter: search on name; per_page max 200; rows carry tag_category {id, name}; no completeness metadata — tags have no meta_* columns) | seo | read |
list_product_tag_categories | TagTools::listProductTagCategories | Tag\Category\Service::all (filter: search on name; per_page max 200; finds the tag_cat_id a tag category with no tags yet is otherwise undiscoverable) | seo | read |
create_product_tag | TagTools::createProductTag | Tag\Tag\WriteService::create (validates tag_cat_id via Tag\Category\Service::get; slug derived from name, not an input) | seo | write (create) |
update_product_tag | TagTools::updateProductTag | Tag\Tag\WriteService::update (name/content per-language merge + order/tag_cat_id/tag_image; slug never regenerated) | seo | write |
list_brands | VendorTools::listBrands | Vendor\Service::all | seo | read |
get_brand | VendorTools::getBrand | Vendor\Service::get | seo | read |
update_brand | VendorTools::updateBrand | Vendor\WriteService::update | seo | write |
Analytics/Sales Tools (7, read-only)
| SDK tool name | Handler method | Domain service called | Scope | Key params |
|---|---|---|---|---|
sales_summary | AnalyticsTools::salesSummary (AnalyticsTools.php:177-196) | Service::summary (Service.php:63-93) | analytics | date_from, date_to; compare = none|yoy|mom|wow|prev_period (default none) |
sales_timeseries | AnalyticsTools::salesTimeseries (AnalyticsTools.php:209-235) | Service::timeseries (Service.php:107-161) | analytics | bucket = day|week|month (default day); metrics ⊆ orders|units|net_revenue|aov (default all) |
sales_breakdown | AnalyticsTools::salesBreakdown (AnalyticsTools.php:256-302) | Service::breakdown (Service.php:188-231) | analytics | dimension = product|category|brand|payment_method|shipping_method|region; sort_by = net_revenue|units|orders (default net_revenue); limit default 25, clamped 1..200; compare |
orders_list | AnalyticsTools::ordersList (AnalyticsTools.php:326-362) | Service::ordersList (Service.php:261-319) | analytics | date_from, date_to; optional single status; opaque cursor; limit default 200, clamped 1..500 |
product_sales | AnalyticsTools::productSales (AnalyticsTools.php:131-164) | Service::productSales (Service.php:354) | analytics | product_ids (max 100); bucket day|week|month (default week) |
customers_stats | AnalyticsTools::customersStats (AnalyticsTools.php:378-400) | Service::customersStats (Service.php:449) | analytics | cohort_by = month|week (default month) |
price_history | AnalyticsTools::priceHistory (AnalyticsTools.php:78-110) | Product\PriceTracking\Service::priceHistory (PriceTracking/Service.php:55-87) | analytics | product_ids (max 100), date_from, date_to |
Content/Blog Tools (4)
| SDK tool name | Handler method | Domain service called | Scope | Write? |
|---|---|---|---|---|
list_articles | BlogTools::listArticles | Cms\Blog\Article\Service::all (filters: is_published, is_promo, author_id, tag_id, title (partial, live only since #579 fixed the blog_mui.title mapping), slug, category_slug, date range; per_page max 20; default returns both drafts and published) | content | read |
get_article | BlogTools::getArticle | Cms\Blog\Article\Service::get (returns the full untruncated body) | content | read |
create_article | BlogTools::createArticle | Cms\Blog\Article\WriteService::create (requires title + banner_image; lands as a draft unless is_published: true) | content | write (create) |
update_article | BlogTools::updateArticle | Cms\Blog\Article\WriteService::update (one language's translation row and/or is_published) | content | write |
Analytics tool contract (common to all 7 handlers): Each handler (a) validates the date range via AnalyticsRequest (strict Y-m-d, from ≤ to, span ≤ 366 inclusive days; AnalyticsRequest.php:22, 30-90), converting ValidationException → ToolCallException (AnalyticsTools.php:408-417); (b) validates its enums against class allow-lists (AnalyticsTools.php:26-57); (c) calls McpAuditLogger::logRead(tool, filters) BEFORE delegating (AnalyticsTools.php:101-105, 156-161, 189-193); (d) returns the domain envelope carrying schema_version ("1.0"), currency "EUR", timezone "Europe/Athens" (Service.php:32, 907-917). price_history merges schema_version onto the PriceTracking payload explicitly (AnalyticsTools.php:109). product_sales cost semantics: margin_pct is null when cost is null; a non-positive acquisition_value is normalised to null before margin calculation, resulting in null margins on those products (since #570, Service.php:392-405).
SEO/Catalog tools: 12 read tools (incl. the two *_stats aggregates, the two *_batch_get tools, and the two product-tag list tools added by #713), 1 orientation tool (get_shop_info), 8 mutating write tools across 4 entity types — category, product, product tag, vendor/brand (create_product_tag is the only create_* tool in this set; there is no delete of any kind); 12 + 1 + 8 = 21. SEO_INSTRUCTIONS (McpServerFactory.php:37-61) states that among THESE tools creating is possible for product tags only — scoped that way, not connector-wide, because a token also holding content receives the blog block too (below), and that set can create articles.
Content/Blog tools: 2 read tools (list_articles, get_article), 1 create tool (create_article), 1 update tool (update_article); 2 + 1 + 1 = 4. content is a separate scope rather than a widening of seo (Scopes.php:12, 21-27) precisely so that blog creation is not granted to every token issued for SEO work. Nothing on the connector — under any scope — can delete.
For the operator/developer curl JSON-RPC acceptance collection, see docs/guides/mcp-connector.md.
Code Flow
Request Pipeline
POST /mcp/c/<token>
|
+-- application/controllers/Mcp::connector($token)
| |-- Switch gate: load registry helper, then isMcpConnectorEnabled() [Mcp.php:26-27]
| | | (registry MCP_CONNECTOR.ENABLED; missing row ⇒ off) [registry_helper.php:597-624]
| | |-- false → show_404(); return [Mcp.php:27-30]
| |-- db_debug suppression: $db->db_debug = false [Mcp.php:38-41]
| | | (prevents CI HTML "Database Error" page from breaking JSON-RPC)
| \-- di()->get(McpRequestHandler::class)->handle($token) [Mcp.php:43]
|
+-- McpRequestHandler::handle($token) [McpRequestHandler.php:41-80]
| |-- TokenGuard::verify($presented) [TokenGuard.php:28-44]
| | |-- empty? → null
| | |-- token matched by indexed sha256-hash equality lookup — `findByHash(hash('sha256', $presented))` → `TokenRepository::findByHash` (`TokenRepository.php:26-37`, `WHERE token_hash = ?`)
| | |-- touch last_used_at ≤ once/60s
| | |-- returns matching row (carries scopes)
| | \-- null → emit 401 generic JSON-RPC -32001 [McpRequestHandler.php:43-48]
| |
| |-- RateLimiter::allow('token:'.$tokenRow->token_hash) [:50-56]
| | |-- fixed-window 60 req/60s, key mcp_ratelimit:{hash}:{minute-bucket}
| | \-- false → emit 429 + Retry-After header JSON-RPC -32029
| |
| |-- McpAuditLogger::setActor($tokenRow->token_hint) [:59]
| |
| |-- new HttpFactory() (Guzzle PSR-17 factories; php-http/discovery never exercised) [:64]
| |
| |-- requestedProtocolVersion(PsrBridge::captureRequest(), $factory) [:66, :89-109]
| | |-- captureRequest() = ServerRequest::fromGlobals; body read into $raw [:91-95]
| | |-- initialize with string params.protocolVersion → ProtocolVersion::tryFrom(); anything else → null [:103-108]
| | \-- seekable body rewound, else rebuilt via createStream($raw) so the SDK can still read it [:97-101]
| |
| |-- McpServerFactory::create(Scopes::parse($tokenRow->scopes ?? null), $version) [:67]
| | |-- Scopes::parse() converts CSV to canonical list; NULL/blank → [seo] [Scopes.php:50-60]
| | |-- setServerInfo, setInstructions, setContainer(di())
| | |-- setLogger(new LogMessageLogger())
| | |-- setSession(($sessionStoreFactory)()) ← lazy: opens Redis only here
| | | |-- sess_driver=redis + valid DSN → CacheSessionStore [container.php:51-61]
| | | \-- else → FileSessionStore at cache/mcp-sessions [container.php:62-66]
| | |-- if $version !== null → $builder->setProtocolVersion($version) [McpServerFactory.php:152-154]
| | |-- buildInstructions(scopes) composes per active scope [McpServerFactory.php:183-197]
| | |-- register get_shop_info always [McpServerFactory.php:157]
| | |-- if seo ∈ scopes: register 20 catalog/write tools (incl. 4 product-tag tools, #713) [McpServerFactory.php:159-164]
| | |-- if analytics ∈ scopes: register 7 read-only analytics tools [McpServerFactory.php:166-168]
| | \-- if content ∈ scopes: register 4 blog-authoring tools (#714) [McpServerFactory.php:170-172]
| |
| |-- SDK Mcp\Server handles JSON-RPC dispatch
| | |-- initialize → mint Mcp-Session-Id, store in session store
| | |-- tools/list → return tool schemas
| | \-- tools/call → dispatch to tool handler
| | |-- read SEO tools → call domain Service, return data
| | | |-- searchProducts() [ProductTools.php:67-146]
| | | | |-- active-by-default scope (active=1,softDelete=0) unless include_inactive [:120-131]
| | | | |-- vendor_id alias / has_meta (FilterByMetaPresence) / updated_since (FilterByDateChangedSince) [:99-118]
| | | | \-- per_page clamped 1-200 [:90]
| | | |-- get_product/search_products include price, is_active, updated_at, stock from coreAttributes() [ProductTools.php:517-527]; compact() (search_products) and view() (get_product, products_batch_get) also project `barcodes` [{barcode, product_code}] via barcodeRefs() [ProductTools.php:473, 508, 566-572]
| | | |-- productsBatchGet(ids[]) [ProductTools.php:182-219] — max 100, WHERE IN, ordered+missing
| | | \-- productsBatchUpdate(items[]) [ProductTools.php:231-274] — max 50, best-effort per row
| | |-- read analytics tools → validate range/enums → McpAuditLogger::logRead() → SalesAnalytics/PriceTracking Service
| | | |-- validate via AnalyticsRequest (date format, from≤to, ≤366 days) [AnalyticsRequest.php:22,30-90]
| | | |-- validate enums against allow-lists [AnalyticsTools.php:26-57]
| | | |-- audit BEFORE delegating via logRead(tool, filters) [AnalyticsTools.php:101-105,etc]
| | | \-- read-through L2 cache (except orders_list), return envelope [Service.php:920-947]
| | |-- write SEO tools (via MergesTranslations::applyMergeUpdate):
| | |-- TranslationMerger::mergedPayload()
| | | \-- fetch ALL language rows, overwrite only target row's changed cols
| | |-- HtmlSanitizer strips script/iframe/on*/javascript: in HTML fields
| | |-- diffFields(): compare string casts; if nothing changed
| | | \-- return {no_changes:true}, skip write + audit
| | |-- WriteService::update() → transactional DB commit
| | | |-- translations via MuiWriteRepository::upsertForEntity (per-language in-place update; never deletes; see SY-23)
| | | \-- category/tag pivots via Category/TagPivotWriteRepository::syncForProduct (products only)
| | |-- McpAuditLogger::log(tool, recordId, changes)
| | | \-- INSERT into user_audit_logs (provider='MCP', masked url, user_id=null)
| | \-- ValidationException → ToolCallException (surfaced to LLM)
| | |-- content (blog) tools → Cms\Blog\Article\{Service,WriteService} (BlogTools.php, #714)
| | | |-- listArticles/getArticle: plain Service reads
| | | |-- createArticle: pre-validates title/banner_image/blog_date ITSELF (no diffFields()
| | | | seam on the create path), then WriteService::create() → transactional DB commit;
| | | | a null return is a swallowed transaction failure, not "not found" [BlogTools.php:282-295]
| | | \-- updateArticle: diffFields() + mergedPayload() as above, but does NOT go through
| | | MergesTranslations::applyMergeUpdate() — the root column `is_published` is
| | | diffed and written inline alongside the translation diff, in ONE update() +
| | | ONE audit->log() [BlogTools.php:329-374]
| |
| |-- PsrBridge::emit(response) → CI_Output (status, headers, raw JSON body)
| |
| \-- Throwable → log_message('error', ...) + emit 500 JSON-RPC -32603Tricky Branches
no_changes idempotency. diffFields() (MergesTranslations.php:80-115) compares string casts of old and new values per field. When no field changes, applyMergeUpdate() returns ['no_changes' => true] and skips both the WriteService call and the audit log insert (MergesTranslations.php:56-58). Verified by CategoryToolsTest.php:113-125, ProductToolsTest.php:107-120, VendorToolsTest.php:83-95.
Generic 401 (no timing oracle). The guard never distinguishes "no active token" from "wrong token" in the response — both return the same generic -32001 error (McpRequestHandler.php:45-46, TokenGuard.php:8-13). Token matching uses an indexed sha256-hash equality lookup (TokenRepository::findByHash at TokenRepository.php:26-37), with no explicit hash_equals comparison call.
429 + Retry-After. When RateLimiter::allow() returns false, McpRequestHandler emits a 429 HTTP response with Retry-After header before the SDK server is constructed (McpRequestHandler.php:50-56). The rate-limit key is per token hash, not per IP.
404 while the connector is switched off. Mcp::connector() loads the registry helper itself ($this->load->ecomnHelper('registry'), Mcp.php:26 — Mcp extends MX_Controller, not Adv_base_controller, so nothing else has loaded it on this request), then calls show_404() and returns immediately unless isMcpConnectorEnabled() is true (Mcp.php:27-30). The gate is the Advisable-only registry setting MCP_CONNECTOR.ENABLED: '1' reads as on, while '0', '' and a missing row read as off (registry_helper.php:597-624), so an environment that has not run the carry-over migration keeps the endpoint closed (and, as the registry is read through its per-language cache, a change is seen only once that cache refreshes — see "Cache timing" under the On/off switch subsection). The admin side asks the same function: index() passes it to the view as connectorEnabled (AdvMcpConnectorSettings.php:43), and the write actions (generate, rotate, revoke) go through guardWrite() (AdvMcpConnectorSettings.php:115-123), which redirects back to settings/mcp_connector without touching any token when the connector is off or the request is not a POST. The retired APP_MCP_CONNECTOR_ENABLED env var is no longer read anywhere on this path.
Session store (K8s vs single-node). The $sessionStoreFactory closure is evaluated lazily inside McpServerFactory::create(), after auth and rate-limit checks pass. On K8s (KEDA multi-pod), CacheSessionStore uses the session Redis so Mcp-Session-Id survives cross-pod routing; on Plesk/single-node, the SDK's own FileSessionStore is used under cache/mcp-sessions. For the full K8s session topology, see SY-29 Deployment Architecture (SY-29:269, 283).
Data Model
mcp_connector_tokens
Created by database/migrations/20260612130000_create_mcp_connector_tokens.php:9-22. Not present in database/initial/initial.sql.
| Column | Type | Notes |
|---|---|---|
id | INT unsigned AI PK | :11 |
label | string(100) default 'default' | :12 |
token_hash | char(64) | sha256 hex of plaintext token — unique index :13, :19 |
token_hint | char(4) | last-4 chars of plaintext, for display :14 |
scopes | varchar(64) NULL | CSV of capability scopes (seo, analytics, content); NULL = legacy seo-only. Added by migration 20260630120000_add_scopes_to_mcp_connector_tokens.php:15-25; forward-only, no rollback. content (#714) added no migration — the column is already an unconstrained CSV string, so Scopes::ALL grew with no schema change |
created_by | int nullable | admin uid that generated it — no FK :15 |
created_at | datetime | :16 |
last_used_at | datetime nullable | touched at most once per 60 s :17 |
revoked_at | datetime nullable | non-null = revoked; indexed :18, :20 |
Indexes: unique on token_hash (:19); index on revoked_at (:20). Multiple non-revoked rows may coexist by design. Repository methods: findByHash(hash) (active row for a hash, :26-37), findById(id) (any row, for rotate, :42-52), allActive() (newest-first list for the admin table, :59-67), touchLastUsed(id) (:72-77), revokeById(id) (:82-88).
Read-only tables (analytics layer)
The SalesAnalytics and PriceTracking services READ (never write) these tables. Schemas are owned by their respective flow docs:
shop_order— money math:total(net products excl VAT/shipping),total_vat(customer-paid grand total incl VAT + shipping; inverted naming), filtered byentry_datetime; also read:transportation_cost,delivery_cost,coupon_value,payway,transport_id,pricing_county,order_currency,status,customer_id| Owned by AD-03 Order Management (Admin)shop_order_basket— line items (qty, subtotal, price, discount_price, product_vat, product_code_id) | Owned by AD-03 Order Management (Admin)product_codes,shop_product,shop_customer— product stock, pricing, customer identity | Owned by AD-02 Product Management (Admin), AD-03 Order Management (Admin)transporters_mui,county_mui,shop_product_mui,shop_vendor_mui,shop_product_category_mui,shop_product_category_lp— multi-language labels and category assignment pivot | Owned by respective AD-02, AD-05 Category Management, AD-19 Vendor Managementprice_tracking— change-only price history log (id, product_id, price_date, price) | Owned by SY-04 Price Tracking
user_audit_logs (shared, MCP write + read audit)
Created by database/migrations/20250509080101_audit_log.php:11-29 (predates MCP; shared with REST/internal audit).
| Column | Type | MCP value |
|---|---|---|
id | INT PK AI | — |
user_id | INT nullable | always null for MCP rows |
username | varchar(255) | 'mcp-connector:<hint>' |
roles | varchar(255) | — |
provider | varchar(255) | 'MCP' |
method | ENUM('GET','POST','PUT','DELETE','PATCH') | always 'POST' |
url | TEXT | site_url('mcp/c/[redacted]') — masked, never plaintext token |
ip_address | varchar(45) | — |
params | JSON | before/after field values, truncated to 2048 bytes per value |
created_at | DATETIME | — |
Indexes: user_method (user_id, method), created_at, user_method_date (user_id, method, created_at) (:24-26). No FK on user_id. MCP write rows set user_id = null, username = 'mcp-connector:<hint>', provider = 'MCP', method = 'POST', and mask the URL (McpAuditLogger.php:46-56). MCP read rows via logRead() use the same shape but params = {tool, filters} with NO changed key (the read/write discriminator, McpAuditLogger.php:70-93). McpAuditLogger calls add() (inherited from AdvAuditModel, through the loaded audit/audit_model) directly — never storeUserLog()/storeRestLog(), which would persist the request URI containing the plaintext token (McpAuditLogger.php:7-14).
Entity tables written by the tools
update_category, update_product, update_product_content, update_brand, create_product_tag, and update_product_tag write through src/Domains/Product/{Category,Product,Tag\Tag,Vendor}/WriteService. The update tools' translation writes hit the *_mui tables via MuiWriteRepository::upsertForEntity($id, $translations, $insertRows) (src/Domains/Support/Repository/BaseMuiWriteRepository.php:48; called from Product\WriteService::update() at src/Domains/Product/Product/WriteService.php:112), which updates each sent language in place, keeps languages and columns that are not sent, and never deletes — see SY-23 MUI Translation Pattern for the upsert contract. create_product_tag instead inserts its one translation row through insertForEntity() in Tag\Tag\WriteService::create() (src/Domains/Product/Tag/Tag/WriteService.php:40). Product category writes hit the category pivot via CategoryPivotWriteRepository::syncForProduct(), and — since #713 — product tag writes hit the sibling tag pivot (shop_product_product_tags) via TagPivotWriteRepository::syncForProduct(); both are called from Product\WriteService::create()/update() (src/Domains/Product/Product/WriteService.php:69-75, 119-125). Unlike the category pivot, shop_product_product_tags has no unique index or foreign keys, so TagPivotWriteRepository deduplicates ids itself before inserting (TagPivotWriteRepository.php:21-26). The schemas of shop_products/shop_products_mui, shop_category/shop_category_mui, and shop_vendor/shop_vendor_mui are documented by the respective product, category, and vendor flow docs, not here (see AD-02 Product Management (Admin), AD-05 Category Management, and AD-19 Vendor Management for full column-level schemas).
create_article and update_article write blog (root columns, incl. is_published) and blog_mui (translations: update_article through the same MuiWriteRepository::upsertForEntity() in-place upsert, called at src/Domains/Cms/Blog/Article/WriteService.php:62; create_article through insertForEntity(), :40) through src/Domains/Cms/Blog/Article/WriteService (#714). Unlike the product/category/vendor writers, WriteService::create()/update() has no category- or tag-pivot branch at all — a connector-created article is never linked to a blog category or tag, and no tool on this connector can add one after the fact (src/Domains/Cms/Blog/Article/WriteService.php).
Domain Layer
Modern Layer (src/Mcp/, namespace Advisable\Mcp\)
26 files (TagTools.php added by #713, BlogTools.php by #714). DI module 'app' pointing at src/Mcp (application/config/container/modules.php:62).
HTTP pipeline (src/Mcp/Http/)
| File | Lines | Responsibility |
|---|---|---|
McpRequestHandler.php | 139 | Orchestrator: token guard → rate limit → set audit actor → build server → SDK dispatch → emit response; maps errors to JSON-RPC codes (-32001, -32029, -32603) |
RateLimiter.php | 55 | Fixed-window 60 req/60 s over cache.l2; key mcp_ratelimit:{hash}:{minute-bucket}, TTL 120 s (RateLimiter.php:18-19, 31-41) |
PsrBridge.php | 43 | captureRequest() = ServerRequest::fromGlobals(); emit() flushes PSR-7 response through CI_Output without re-encoding (PsrBridge.php:22-42) |
Auth (src/Mcp/Auth/)
| File | Lines | Responsibility |
|---|---|---|
TokenService.php | 105 | generate(string $label, array $scopes, ?int $createdBy) inserts a new active row (never revokes) and returns plaintext once (:29-43); revoke(int $tokenId) (:48-51); rotate(int $tokenId, ?int $createdBy) = revokeById + regenerate same label/scopes, returns null if id unknown/already-revoked (:57-71); list() returns active tokens with parsed scopes (:78-90); randomToken() unchanged 43-char base64url (:96-99) |
TokenGuard.php | 56 | verify() unchanged externally; now findByHash() + returns row carrying scopes (:28-44) |
TokenRepository.php | 89 | Methods: findByHash(hash) (active row for a hash, :26-37), findById(id) (any row, for rotate, :42-52), allActive() (newest-first list for the admin table, :59-67), touchLastUsed(id) (:72-77), revokeById(id) (:82-88) |
Scopes.php | 75 | Consts SEO='seo', ANALYTICS='analytics', CONTENT='content' (:31-33, #714), ALL=[seo,analytics,content] — append-only, order fixes the stored CSV byte layout (:42); parse(?string $csv): list<string> — NULL/blank → [seo] (legacy BC), else trim+lowercase, filter to ALL canonical order, empty → [seo] (:50-60); format(array): string → canonical CSV, unknown dropped, empty → seo (:68-74). Verified by tests/Unit/Mcp/Auth/ScopesTest.php:12-77 |
Server (src/Mcp/Server/)
| File | Lines | Responsibility |
|---|---|---|
McpServerFactory.php | 836 | Builds Mcp\Server: create(array $scopes = [Scopes::SEO], ?ProtocolVersion $protocolVersion = null): Server (:141) registers the UNION of scope-gated tool sets (:141-175) and calls setProtocolVersion() when a version is passed (:152-154) and sets server info/instructions, DI container, PSR-3 logger, lazy session store; buildInstructions(scopes) composes instructions per active scope (:183-197); registerAnalyticsTools() (:215-384), registerTagTools() (#713, 4 product-tag tools, :580-624), registerBlogTools() (#714, :666-718) + articleListSchema() (:720-744); registers get_shop_info always, seo tools when seo ∈ scopes, analytics tools when analytics ∈ scopes, blog tools when content ∈ scopes; provides JSON schema helpers. Consts: SEO_INSTRUCTIONS (formerly INSTRUCTIONS, :37-61) — rewritten by #713 to name create_product_tag as its create exception, then scoped by #714 to "among THESE tools" so it cannot contradict the blog block; ANALYTICS_INSTRUCTIONS (:63-69); CONTENT_INSTRUCTIONS (:81-107, #714); WRITE_NOTE (:113) — rewritten by #713 from a blanket to a per-tool "THIS tool ... cannot create one", which is why #714 needed no separate article variant; CREATE_NOTE (:115) |
CacheSessionStore.php | 99 | SDK SessionStoreInterface over CacheAdapterInterface; exists/read/write/destroy all wrap try/catch → falsey on error (graceful degrade, #337); gc() returns [] (TTL-based); key session:<uuid-rfc4122>, TTL 3600 (CacheSessionStore.php:39-98) |
Tools (src/Mcp/Tools/)
| File | Lines | Responsibility |
|---|---|---|
ShopTools.php | 63 | get_shop_info: registry site title + LanguageResolver; degrades to '' on registry failure (#332, ShopTools.php:39-62) |
CategoryTools.php | 293 | list_categories, get_category, update_category; injects Category\{Service,WriteService,ListRequest} (CategoryTools.php:17-293) |
ProductTools.php | 591 | search_products (filters: query, category_id, brand_id/vendor_id, has_meta, is_active, include_inactive, updated_since, barcode + barcode_match exact (default) or partial; per_page max 200), get_product (+ read-only core fields: price, is_active, updated_at, stock), update_product (title/meta + category_ids replace + brand reassign + since #713 tag_ids replace), update_product_content (description/short/ingredients/usage/extra), products_batch_get (max 100, WHERE IN, ordered+missing), products_batch_update (max 50, best-effort per row); READ_RELATIONS includes productCodes, barcodes (#1010, ProductTools.php:35) and, since #713, 'tags' => ['translations'] (ProductTools.php:35) — both compact() (backs search_products) and view() (backs get_product/products_batch_get) project the loaded tags (ProductTools.php:472, 507; pinned by test_search_products_projects_tags_so_the_eager_load_is_not_wasted, ProductToolsTest.php:486) and barcodes (ProductTools.php:473, 508; pinned by test_search_row_projects_barcodes and test_get_product_projects_barcodes_and_empty_when_none, ProductToolsTest.php:759, 778); injects Vendor\Service for brand validation (ProductTools.php:11, 58) |
VendorTools.php | 121 | list_brands, get_brand, update_brand; "brand == vendor" (VendorTools.php:18, 37-91) |
TagTools.php | 478 | list_product_tags, list_product_tag_categories, create_product_tag, update_product_tag (#713); injects Tag\Tag\{Service,WriteService} + Tag\Category\Service; tags carry no meta_* columns so none of the SEO-completeness machinery applies; create/update are inlined rather than routed through applyMergeUpdate() (create has no existing row to merge against; update carries non-translation columns) (TagTools.php:37-478) |
AnalyticsTools.php | 448 | The 7 read-only analytics handlers; ctor injects PriceTracking\Service, SalesAnalytics\Service, McpAuditLogger, LanguageResolver (:59-65) |
BlogTools.php | 578 | list_articles, get_article, create_article, update_article over blog/blog_mui (#714); ctor injects Cms\Blog\Article\{Service,WriteService}, TranslationMerger, HtmlSanitizer, McpAuditLogger, LanguageResolver, DescriptionMetrics (:91-100). Re-derives HtmlSanitizer/ToolResult::enforceLengths()/non-empty checks by hand for createArticle() because no create path runs through diffFields() anywhere in the repo; updateArticle() does NOT use MergesTranslations::applyMergeUpdate() (it would report no_changes on a publish-only change to the root is_published column). listArticles() exposes a partial title filter only because #579 corrected the domain mapping to blog_mui.title |
MergesTranslations.php | 126 | Trait shared by all five write-capable tool classes (Category/Product/Vendor fully via applyMergeUpdate(); Tag and Blog partially — only diffFields()/translationFor()/runWrite(), since their create/update paths are inlined): applyMergeUpdate(), diffFields(), runWrite() (ValidationException → ToolCallException), translationFor() (MergesTranslations.php:19-126) |
Support (src/Mcp/Support/)
| File | Lines | Responsibility |
|---|---|---|
TranslationMerger.php | 90 | mergedPayload() builds the full multi-language row set with only the target row's changed columns overwritten. Since #857 translation writes are an in-place upsert (MuiWriteRepository::upsertForEntity()) that never deletes, so the full-row merge is no longer load-bearing: the class docblock calls the result "correct under upsert" and keeps it so every other language and unspecified column (slug/url, non-editable columns) is sent byte-identical (TranslationMerger.php:9-18); mergedPayload() still sends all rows (:66-81) |
HtmlSanitizer.php | 34 | Regex-based XSS strip (script/iframe/object/embed + content, on* handlers, javascript: URLs); keeps img/tables/headings (HtmlSanitizer.php:17-33) |
LanguageResolver.php | 45 | defaultLang() = config_item('language_abbr') ?: 'el'; allowed() = array_keys(lang_uri_abbr); resolve() rejects unknown codes (LanguageResolver.php:18-44) |
ArrayListInput.php | 25 | Adapts an assoc array to the ->get($key) shape GenerateListRequest::generate() expects (ArrayListInput.php:21-24) |
LogMessageLogger.php | 74 | PSR-3 AbstractLogger forwarding to log_message() (#329); folds exceptions into "[MCP] <msg> | <Class>: <msg> @ file:line"; no-ops if log_message absent (LogMessageLogger.php:34-73) |
ToolResult.php | 64 | enforceLengths(): HARD limits — throws ToolCallException when meta_title > 65 or meta_description > 150 chars, naming the actual and permitted length so the model can rewrite and retry; the public META_TITLE_MAX/META_DESCRIPTION_MAX constants are the single source McpServerFactory reads for the tool-schema advice, so the limit and the advice cannot drift (ToolResult.php:20-21, 40-63) |
DescriptionMetrics.php | 84 | Computes accurate HTML-stripped clean-text completeness metrics (length, wordCount, isComplete) for the MCP list projections; the accurate per-row side of the completeness rule vs the server-side raw-CHAR_LENGTH approximation; reads APP_MCP_DESCRIPTION_COMPLETE_MIN_CHARS (default 120) (DescriptionMetrics.php:19-84) |
Domain Specifications used by Product tools (src/Domains/Product/Product/Repository/Specification/)
| File | Lines | Responsibility |
|---|---|---|
FilterByMetaPresence.php | 45 | Locale-scoped id NOT IN / IN (SELECT product_id FROM shop_product_mui WHERE lang=? AND (meta_title set OR meta_description set)) subquery spec; has_meta=false uses NOT IN; products with no translation row for the locale are treated as missing-meta (FilterByMetaPresence.php:24-45) |
FilterByDateChangedSince.php | 25 | shop_product.date_changed >= gte spec for incremental processing (FilterByDateChangedSince.php:15-25) |
Audit (src/Mcp/Audit/)
| File | Lines | Responsibility |
|---|---|---|
McpAuditLogger.php | 132 | setActor($hint); log($tool, $recordId, $changes) logs write operations (masked URL, user_id=null, provider='MCP'), never throws (:35-60); logRead(string $tool, array $filters) logs read operations with same shape but params = {tool, filters}, no changed key (:70-93); truncateFilters() caps string values at 2048 bytes (:102-111) |
DI container (src/Mcp/container.php)
Autowire + autoconfigure + public (:13-17). Session store is wired conditionally (:51-66): when sess_driver === 'redis' AND sess_save_path matches ^(tcp|tls|unix)://, registers a dedicated mcp.session_cache RedisAdapter (keyPrefix 'mcp' → keys under cache:mcp:, disjoint from phpredis session keys) + CacheSessionStore; else FileSessionStore at cache/mcp-sessions. McpServerFactory receives the store via service_closure (lazy) and serverVersion from app_version config (:68-70). The session store intentionally uses the session Redis (volatile-lru, AOF + Sentinel), never the L2 cache Redis (allkeys-lru, no persistence), to prevent session eviction (#337, CacheSessionStore.php:22-29). Tool classes are registered individually as public services for the SDK to resolve at tool-call time (:84-90); #714 added $services->set(Tools\BlogTools::class); (:90) — its DI dependencies (Cms\Blog\Article\{Service,WriteService}, TranslationMerger, HtmlSanitizer, McpAuditLogger, LanguageResolver, DescriptionMetrics) are all already-registered services, so no other container file changed.
Analytics Layer (src/Domains/Order/SalesAnalytics/, read-only)
Modern layer: SalesAnalytics domain + Service/Repository. DI at src/Domains/Order/container.php:107-116.
| File | Lines | Responsibility |
|---|---|---|
Service.php | 959 | Reporting aggregates over shop_order + shop_order_basket; SCHEMA_VERSION = '1.0' (:32); read-through L2 cache TTL 300 s (:35) via cached()/cacheKey() (:931-958, key mcp_sales:<tool>:<md5(serialize(ksort(filters)))>); orders_list intentionally NOT cached (:269-272). Methods: summary(from, to, compare?), timeseries(from, to, bucket?, metrics?), breakdown(from, to, dimension, sort_by?, limit?, compare?), ordersList(from, to, status?, cursor?, limit?), productSales(product_ids[], bucket?), customersStats(cohort_by?). Envelope adds schema_version, currency EUR, timezone Europe/Athens (:907-917) |
Repository/Repository.php | 896 | Bound to shop_order via NullRelationConfigurator, entity= (`:38-49`); thin aggregate queries; SQL safety: statuses/lang/dates escaped via `getDb()->escape()` (`:871-895, 384, 705`); enums allow-listed upstream; MUI joins lang-scoped ( AND mui.lang = <esc> ``) and MIN()-wrapped for ONLY_FULL_GROUP_BY (:809-845) |
AnalyticsRequest.php | 125 | Value object; MAX_RANGE_DAYS=366 (:22); strict Y-m-d via createFromFormat + getLastErrors (:36-59); from ≤ to and span guards throw ValidationException (:69-86) |
Bucket.php | 70 | Day → DATE(col), week → YEARWEEK(col, 3) (ISO), month → DATE_FORMAT(col, '%Y-%m') (:62-69); column always caller-supplied |
SaleStatuses.php | 75 | Registry group MCP_ANALYTICS, key SALE_STATUSES (:23-24); DEFAULT = [PENDING_ACCEPTED, PAID_SENT, SENT, INVOICED] (:32); fromRegistry() reads CSV, falls back to DEFAULT (:54-64) |
Price Tracking (src/Domains/Product/PriceTracking/)
Extends Product domain. Service + Repository (new). DI at src/Domains/Product/container.php:389-403 (the PriceTracking block also registers PriceDropVerdictCalculator, CurrentPrice, PriceDropStore, PriceDropRefresher, GraphService and Jobs\TrackPrices; the price-drop verdict classes are owned by SY-04 Price Tracking).
| File | Lines | Responsibility |
|---|---|---|
Service.php | 142 | priceHistory(product_ids[], date_from, date_to) — read-only log via Repository; on_promo always null (never recoverable historically), promo_history_available:false (:70-85); tracking_enabled from Options per-product; earliest_date per product |
Repository/Repository.php | 93 | changesInRange(product_ids[], from_date, to_date): list<RowType> (:31-55); earliestDates(product_ids[]): array<product_id => date> (:66-92) |
Legacy Layer
Entry controller — application/controllers/Mcp.php (45 lines)
Mcp extends MX_Controller with ApiEndpointTrait (:14-16). Single action connector(string $token) (:21). Switch gate at :26-30 (loads the registry helper, then show_404() unless isMcpConnectorEnabled()); db_debug suppression at :38-41; delegates to McpRequestHandler at :43.
Admin settings controller — ecommercen/settings/controllers/AdvMcpConnectorSettings.php (130 lines)
AdvMcpConnectorSettings extends Admin_c (:23). Constructor RBAC: allowRole([AUTH_ROLE_ADVISABLE, AUTH_ROLE_DEVELOPER, AUTH_ROLE_ADMIN], $this->sessionRoles) else error_401() (:29-32). index() renders a token list + connectorEnabled (= isMcpConnectorEnabled(), :43) + availableScopes = Scopes::ALL + one-time newUrl from flashdata (:37-55). generate() reads label + postedScopes() (:58-73); rotate($id) (:76-87); revoke($id) by id (:90-98). postedScopes() intersects posted checkboxes with Scopes::ALL, falls back to [seo] (:107-112). guardWrite() requires isMcpConnectorEnabled() and the POST method (:115-123). This controller manages tokens only — it does not own the on/off switch, which is the Advisable-only MCP_CONNECTOR.ENABLED setting on settings/only_advisable (see the "On/off switch" subsection below); its docblock says so (:19-21). Scopes::ALL grew to include content under #714 with no code change to this controller — availableScopes, postedScopes() and the generate-form checkboxes are all scope-set-agnostic (AdvMcpConnectorSettings.php; the file's own docblock at :10-16 now spells out all three scopes).
HMVC subclass — application/modules/settings/controllers/Mcp_connector.php (5 lines)
php
class Mcp_connector extends AdvMcpConnectorSettings {}This is the class the HMVC dispatcher actually resolves to. Routes settings/mcp_connector(/...) map to it via routes.php:190-191, 207-208. It is an empty subclass that inherits everything from AdvMcpConnectorSettings, including the constructor RBAC.
Admin view — application/views/admin/settings/mcp_connector.php (124 lines)
When connectorEnabled is false (the connector is switched off) renders a disabled notice (settings.mcp_connector.disabled_notice, now "The MCP Connector is disabled. It can be enabled by Advisable.") in place of the token UI (:15-19; the token UI is the else branch, :21-120); otherwise a per-row token table (label, masked URL, scope badges t('settings.mcp_connector.scope_'.$scope), created, last-used, Rotate + Revoke forms) (:49-90); Generate form with label input + scope checkboxes (seo pre-checked) + one-time reveal (:94-115). All output html_escape()d.
Admin menu — application/config/admin_menu.php:164-170
route: 'settings/mcp_connector', roles: [AUTH_ROLE_ADVISABLE, AUTH_ROLE_DEVELOPER, AUTH_ROLE_ADMIN], group: 'SETTINGS'. Menu roles and controller constructor RBAC are consistent.
On/off switch — MCP_CONNECTOR.ENABLED (#824)
The connector's single on/off switch is the Registry setting MCP_CONNECTOR.ENABLED, stored '1'/'0'. It replaced the APP_MCP_CONNECTOR_ENABLED env var, which epic #312 had deliberately kept out of the admin UI.
| Piece | Where | Behaviour |
|---|---|---|
| Gate | isMcpConnectorEnabled(), ecommercen/helpers/registry_helper.php:597-624 | (bool) ($registry->value('MCP_CONNECTOR', 'ENABLED') ?? 0). Loads the registry library itself, because Mcp is not an Adv_base_controller and application/config/autoload.php autoloads only database as a library. '0', '' and a missing row read as off. Called by Mcp::connector() (Mcp.php:26-30) and by AdvMcpConnectorSettings::index() (:43) and guardWrite() (:118) |
| Writer | Adv_settings::only_advisable(), ecommercen/settings/controllers/Adv_settings.php:2376-2388 | setValue('MCP_CONNECTOR', 'ENABLED', (int)(bool) post('mcpConnectorEnabled')), only inside allowRole([AUTH_ROLE_ADVISABLE], $this->sessionRoles), then pscache->delete_all() (:2387) so every language's copy is rebuilt on the next request |
| Panel | application/views/admin/settings/only_advisable.php:318-337 | "MCP Connector" panel with the mcpConnectorEnabled checkbox, rendered for every role that reaches the page, which is Advisable only: _remap() refuses every other session with 401 on GET and POST (Adv_settings.php:44-57, list :65-73, #1054). Render var mcpConnectorEnabled (Adv_settings.php:2548-2549, the same truthiness as the gate, so the box shows what is enforced) and trim rule (:2615). Lang keys eshop.admin.only_for_advisable.enable_mcp_connector.header and .label |
| Seed | database/migrations/20261002120000_add_mcp_connector_enabled_registry_key.php | Forward-only, one-time carry-over of each environment's env value (below) |
Guarded by page and by key. settings/only_advisable is Advisable-only in the admin menu (application/config/admin_menu.php:371-377, roles => [AUTH_ROLE_ADVISABLE]), and since #1054 Adv_settings::_remap() also refuses every non-Advisable session with 401 on GET and POST before the action runs (Adv_settings.php:44-57, list :65-73), although Adv_settings::__construct() still admits AUTH_ROLE_ADMIN (:23). The write stays wrapped in allowRole([AUTH_ROLE_ADVISABLE], $this->sessionRoles) (:2471): a session without the Advisable role does not write the key at all, so the stored value — or the absence of a row — stays exactly as it was, and an unposted checkbox is never coerced to 0. This is now a second line of defence, since such a session no longer reaches the page (the earlier gap, where the rest of the page still saved for an admin, is closed by #1054; see Known Issue 11). Pinned by AdvOnlyAdvisableMcpConnectorGuardTest.
Carry-over migration. 20261002120000_add_mcp_connector_enabled_registry_key.php reads $_ENV['APP_MCP_CONNECTOR_ENABLED'] once and maps it with the migration's private toInt() exactly as the runtime env() in public/index.php:32-55 reads it — true/(true)/1 ⇒ 1; false/(false)/0/empty/absent ⇒ 0 — then inserts the row with INSERT … SELECT … WHERE NOT EXISTS, so it never overwrites an existing row (for example one a fork added by hand, or a value Advisable has already set). It cannot call env() for this: migrator.php never loads public/index.php, so inside a migration env() is cakephp/core's raw-string version, and (bool) of the string 'false' — what .env.example used to ship — would be TRUE and switch the connector on. The equivalence with the runtime holds for a variable defined in one place: migrator.php:8 loads .env with createImmutable and public/index.php:29 with createMutable, so a variable set in both the process environment and .env with different values would read as the process value in the migration and as the .env value at runtime — shipped setups never do this. The mapping lives in the migration itself rather than in src/, so a later refactor of src/ cannot break migrate on a fresh install. Deploys run the migration at container start (.docker/scripts/deploy/init_migrate.php:6); code that goes live before it sees no row, so the connector stays off until it has run. Once an environment has run it, the .env line can be deleted (.env.example no longer lists it); a fresh install never set the variable and starts off. When the runtime first sees the seeded row is covered under "Cache timing", next.
Cache timing. Saving the switch clears the whole pscache (Adv_settings::only_advisable(), Adv_settings.php:2387), so every language's copy is rebuilt from the table on the next request and a change applies at once. Without that clear, the gate reads the registry through pscache, which keeps one copy per language (application/libraries/Pscache.php:208-212; default TTL 86400 s, application/config/cache.php:7; no caching in the development environment). Without the save's clear, a change is seen only once the copy a request reads refreshes: Registry::live() refreshes the current language's copy on every admin request (ecommercen/core/Adv_admin_controller.php:60, so the redirect that follows a save refreshes the saving admin's language only) and on cron runs (application/controllers/Cronjob.php:33; 24 job classes call it too, for example ecommercen/job/libraries/AdvCancelIncompleteOrders.php:43); otherwise the TTL does. The endpoint reads the default language's copy, so a switch-off saved from another admin language stays live until one of those refreshes reaches that copy. That needs an admin language other than the default, which the stock config does not have (application/config/languages.php:5, 17). The migration inserts with raw SQL and refreshes nothing, so a cache populated before it keeps reading the row as missing — off — until one of those happens: an environment that had the connector on can answer 404 on /mcp/c/<token> for a while after the deploy. The #824 deploy closes that window with one full pscache clear right after migrate (php cli.php cronjob/clearAllSiteCache → Cronjob::clearAllSiteCache(), application/controllers/Cronjob.php:591-594 → clearCache(), ecommercen/helpers/pscache_helper.php:34-95 → clearPsCacheArray(), :4-17 → Pscache::delete_all(), application/libraries/Pscache.php:407-427). It is a full clear rather than delete_group('registry_model') because the copy the endpoint reads is the default language's. Each cache key starts with the request's language_abbr (application/libraries/Pscache.php:210). /mcp/c/<token> has no language segment, so MY_Lang leaves language_abbr at the configured default (application/core/MY_Lang.php:55-80). Pscache::delete_group() deletes only the copies of the languages in admin_languages (application/libraries/Pscache.php:393), so it reaches that copy only where the default language is also an admin language.
Audit model — ecommercen/audit/models/AdvAuditModel.php (loaded as audit/audit_model)
McpAuditLogger loads the stock Audit_model (application/modules/audit/models/Audit_model.php, an empty subclass of this model) by its module name audit/audit_model — never as audit/AdvAuditModel, which the HMVC loader cannot resolve, so no audit row would be written (#866) — and calls add() directly (the GenericWriteModel trait method, ecommercen/core/models/GenericWriteModel.php:5-9 — a plain $this->db->insert($this->table, $data)). It does not call storeUserLog() or storeRestLog(), which would persist the request URI containing the plaintext token. The masked URL is built with $ci->config->site_url(), not the global site_url() of the url helper, which an MCP request does not load. Retention via the shared AdvAuditModel::cleanUpAudit() (:190-195).
Configuration
| Key | Type | Default | Citation | Role |
|---|---|---|---|---|
MCP_CONNECTOR.ENABLED | Registry (Advisable-only) | 0 (off) — no row ⇒ off | seeded once by database/migrations/20261002120000_add_mcp_connector_enabled_registry_key.php; read through isMcpConnectorEnabled() (registry_helper.php:597-624) at Mcp.php:26-30, AdvMcpConnectorSettings.php:43, 118; written by Adv_settings::only_advisable() (Adv_settings.php:2381-2382) for sessions holding AUTH_ROLE_ADVISABLE only | Gates the entire feature — off ⇒ 404 on connector; off ⇒ admin write actions blocked. Replaces the retired APP_MCP_CONNECTOR_ENABLED env var (#824) |
APP_MCP_ANALYTICS_ID_SECRET | env | empty | .env.example:258-261; read at src/Domains/Order/SalesAnalytics/Service.php:617 | HMAC salt for orders_list opaque customer_id. Precedence: env → CI encryption_key (:619-620) → throws RuntimeException if neither (:623-628), surfaced as ToolCallException (AnalyticsTools.php:357-361) |
app_version | CI config | '1.0.0' fallback | src/Mcp/container.php:21 | MCP server version reported in initialize response |
sess_driver | CI config | — | container.php:22, 51 | Selects CacheSessionStore (redis) vs FileSessionStore |
sess_save_path | CI config | — | container.php:23, 51, 56 | Redis DSN for the dedicated MCP session cache |
language_abbr | CI config | 'el' | LanguageResolver.php:19 | Default lang when tool caller omits it |
lang_uri_abbr | CI config | — | LanguageResolver.php:28 | Allowlist of accepted language codes |
SITE/TITLE | Registry | — | ShopTools.php:49 | Shop name returned by get_shop_info |
APP_MCP_DESCRIPTION_COMPLETE_MIN_CHARS | env | 120 | read in src/Mcp/Support/DescriptionMetrics.php and src/Domains/Product/container.php | Minimum clean-text length for a description to count as "complete". Feeds the MCP per-row projection (accurate, clean text) AND the DI-injected threshold the domain Services use for the has_complete_description filter / incomplete_description stat (raw-length approximation) — same number on both sides |
MCP_ANALYTICS / SALE_STATUSES | Registry | CSV | Default PENDING_ACCEPTED,PAID_SENT,SENT,INVOICED | Registry group MCP_ANALYTICS, key SALE_STATUSES; filtered statuses for sales summaries. SaleStatuses.php:23-24, 32, 54-64 |
Hard-coded constants: SalesAnalytics\Service::CACHE_TTL = 300, SCHEMA_VERSION = '1.0' (Service.php:35, 32); AnalyticsRequest::MAX_RANGE_DAYS = 366 (AnalyticsRequest.php:22); analytics tool bounds — product_ids max 100; breakdown limit 25 default / 1..200 clamped; orders_list limit 200 default / 1..500 clamped; RateLimiter::LIMIT = 60, WINDOW_SECONDS = 60 (RateLimiter.php:18-19); CacheSessionStore TTL 3600 s (CacheSessionStore.php:42); McpAuditLogger::VALUE_MAX_BYTES = 2048 (McpAuditLogger.php:17); ToolResult HARD meta limits 65/150 chars (META_TITLE_MAX/META_DESCRIPTION_MAX, public const, also read by McpServerFactory for the schema advice; aligned with Seo\CustomMetaTag\Validator) (ToolResult.php:20-21).
Admin i18n keys: 12 keys × 8 language files added to ecommercen/language/*/adv_advisable_lang.php (:3650-3661 Greek as reference): label, scopes_col, scope_seo, scope_analytics, scope_content, tokens_heading, no_tokens, col_actions, generate_heading, select_scope_hint, generate_new, rotate_confirm. scope_content (#714) is the only key #714 added — the other 11 predate it (epic #403). The admin view (mcp_connector.php) looks the key up generically as t('settings.mcp_connector.scope_' . $scope), so no view change was needed to render the new scope's label/checkbox. #824 added two keys to the same 8 files — eshop.admin.only_for_advisable.enable_mcp_connector.header and .label, the panel heading and checkbox label on settings/only_advisable (Greek :2642-2643) — and reworded settings.mcp_connector.disabled_notice in all 8 (Greek :3635), which used to tell the reader to set the env var and now reads "The MCP Connector is disabled. It can be enabled by Advisable."
The on/off switch is read from the Registry through isMcpConnectorEnabled(), not from the environment (#824): Advisable toggles it on settings/only_advisable with no deploy, while the settings/mcp_connector page still manages tokens only. APP_MCP_CONNECTOR_ENABLED is retired — nothing reads it at runtime; only the carry-over migration reads it, once (see "On/off switch" under Legacy Layer).
Client Extension Points
The connector is upstream code in src/Mcp/. Client repos cannot modify src/ directly. To override behavior in a client repo:
- Override individual tool classes (e.g.,
Custom\Mcp\Tools\ProductTools) and register DI aliases incustom/Domains/container.php. - Override
McpServerFactoryto add custom tools or change the server instructions. - Custom tools should follow the same
MergesTranslations/TranslationMergerpattern: callrequireTargetRow()before writing — without it,mergedPayload()silently drops an edit to a language that has no stored row (there is no row to merge it onto,TranslationMerger.php:70-78), and a hand-built payload would make the upsert INSERT that language (BaseMuiWriteRepository.php:56-59); then build the payload withmergedPayload(), so every write sends complete translation rows (the upsert would keep unsent languages anyway; see rule 2).
No client-specific tool classes exist at the time of writing.
Business Rules
Edit-first surface, two narrow create exceptions, no delete at all. Every tool updates an existing entity except
create_product_tag(#713, product tags only, underseo) andcreate_article(#714, undercontent). There is still no delete tool of any kind, under any scope. BecausebuildInstructions()concatenates the blocks a multi-scope token holds, each block scopes its own create claim to the tools it describes (SEO_INSTRUCTIONSMcpServerFactory.php:37-61,CONTENT_INSTRUCTIONS:81-107) andWRITE_NOTE(:113) is phrased per-tool ("THIS tool ... cannot create one") rather than per-connector.delete_product_tagwas deliberately NOT added:DELETE /rest/product/tag/{id}already orphans pivot rows today (no FK/cascade onshop_product_product_tags, andTag\Tag\WriteService::delete()has no in-use guard, unlike the legacyAdv_product_tags_model::delete()it descends from) — seedocs/decisions/713-mcp-product-tag-tools.md.Translation writes send complete rows — a guard since #857, no longer what keeps the other languages intact.
TranslationMerger::mergedPayload()rebuilds every stored language's row from the entity the tool has just read, with only the target row's changed columns overwritten (TranslationMerger.php:66-81). Before #857 that was load-bearing: the replace-all write deleted any language left out of the payload and lost any column left out of a row. NowupsertForEntity()updates each sent language in place with only the columns its row carries, leaves unsent languages alone and never deletes (BaseMuiWriteRepository.php:33-78; contract in SY-23 MUI Translation Pattern). None of the fiveWriteService::update()paths the connector reaches checks a translation row for more than itslang(each domain'sValidator::validateTranslations()) or regenerates a slug (generateMuiSlugs()runs increate()only), so a row carrying only the changed columns would store the same result. #857 kept the merge anyway, leaving its removal as a separate simplification (docs/decisions/857-mui-upsert-in-place.md): the stored result then does not depend on which columnsupdate()writes (BlogTools.php:332-335). Its cost is a wider lost-update window (Known Issue 19). The connector never adds a language — the target row must already exist (rule 9) and only stored languages are sent. Absent a concurrent write, a single-field, single-language edit leaves every other language byte-identical.no_changesidempotency. If no field value changes (after string-cast comparison), the write service call and the audit log are both skipped (MergesTranslations.php:56-58).name/titlerequired. An empty or whitespace-only name/title throwsToolCallExceptionimmediately (MergesTranslations.php:91-93).HTML fields are sanitized.
description,extra_description,ingredients,usage,short_descriptionare passed throughHtmlSanitizerbefore the diff (MergesTranslations.php:87-89).meta_title/meta_descriptionmay be cleared, but an over-length value is a HARD reject, not a warning (#575). An empty string clears the field. Ameta_title> 65 chars ormeta_description> 150 chars throwsToolCallExceptionat the write boundary —ToolResult::enforceLengths()— and writes nothing; it is never silently trimmed, because a server-side trim would just write the same cut text the storefront renders, one layer earlier. The sameToolResult::META_TITLE_MAX/META_DESCRIPTION_MAXconstants drive both the enforced limit and the tool-schema advice shown to the LLM, so they cannot drift (McpServerFactory.php:827-835;ToolResult.php:20-21, 40-63).update_product.category_idsis a full-replacement set. The array is sorted, deduped, compared to the current set, then passed asdata['categories']to the WriteService forsyncForProduct()(ProductTools.php:327-334). The LLM is instructed to callget_productfirst (McpServerFactory.php:510).Brand validation before product update.
update_productvalidates the suppliedbrand_idviaVendor\Service::get()before building the write payload (ProductTools.php:354-362).Language must already have a translation row.
LanguageResolver::resolve()rejects unknown codes;TranslationMerger::requireTargetRow()throws if the target language has no existing row. MVP supports editing existing languages only (LanguageResolver.php:31-44,TranslationMerger.php:43-55).Product writes are transactional. Translations + category pivot + tag pivot + scalar update commit together via
writeRepository->transactional()(src/Domains/Product/Product/WriteService.php:104-128); since #713 the same transactional block also syncs the tag pivot via$this->tagPivotWriteRepository->syncForProduct()(:123-125).ValidationException surfaces to the LLM.
runWrite()catchesValidationExceptionand converts it toToolCallExceptionso the LLM receives a structured error rather than a 500 (src/Mcp/Tools/MergesTranslations.php:118-125).Rate limit is per-token, not per-IP. The rate-limit key includes the token hash, not the client IP (
RateLimiter.php:31-32).No domain events fired. Tool writes go directly to
WriteService::update()in-process. No CI hooks or domain listeners are triggered (src/Mcp/Tools/*).Search defaults to active, non-deleted. When neither
is_activenorinclude_inactiveis set,searchProducts()injectsactive=1andsoftDelete=0. An explicitis_activevalue overrides the default for that field.include_inactive=truelifts the entire scope, returning all products regardless of status (ProductTools.php:120-131).brand_idandvendor_idare aliases;brand_idwins. Both map toshop_product.vendor_id(vendorIdfilter). When both are supplied,brand_idtakes precedence:$vendor = $brand_id ?? $vendor_id(ProductTools.php:99-103).has_metasemantics: products with no translation row count as "missing meta".has_meta=falseuses a NOT IN subquery (FilterByMetaPresence) againstshop_product_muifor the active locale. Products with no_muirow at all for the locale are matched by NOT IN — they are treated as missing meta, which is the correct behaviour for SEO-backlog discovery (FilterByMetaPresence.php:8-22, 42-43,ProductTools.php:104-107).updated_sinceis normalised; invalid dates throw.normalizeSince()passes the input throughstrtotime()→date('Y-m-d H:i:s'). An unparseable string throwsToolCallExceptionwith a human-readable message (ProductTools.php:444-452).per_pagefor products is clamped to 200.min(max($per_page,1), MAX_PER_PAGE)whereMAX_PER_PAGE=200(ProductTools.php:26,90). Brands remain capped at 20;list_categoriesis capped at 200 (McpServerFactory.php:751, 768).Read-only core fields are never writable.
price,is_active,updated_at, andstockare appended to everyget_productandsearch_productsresponse bycoreAttributes()(ProductTools.php:517-527), but no tool accepts them as input.stockis the sum ofstockover active (active=1), non-soft-deleted (soft_deleted=0) product codes viastockTotal()(:529-539).barcodesis a relation projection, not one of these core fields: compact() and view() add it frombarcodeRefs()(ProductTools.php:473, 508, 566-572).products_batch_getordering, missing list, and active-agnostic behaviour. Returns found products in the same order as the requestedids. Not-found ids are collected inmissing. Active/visibility filters are NOT applied — the ids are explicit, so inactive or soft-deleted products are returned if their ids are in the request. Caps atMAX_BATCH_GET=100; empty input returns{data:[],missing:[]}without querying (ProductTools.php:182-219).products_batch_updateis best-effort per row, returning the unified batch shape. Updates title + meta only; category, brand, and (since #713) tag reassignment are not batchable —productsBatchUpdate()callsupdateProduct()positionally with only 8 arguments and never passestag_ids(ProductTools.php:255-266;McpServerFactory.php:552). Returnsdata[](theupdate_productresult per applied row),results[](per-item{id|index, status, error?}) andmissing[](ids not found) — the same shape ascategories_batch_update. A failing or not-found row does not abort the others; each successfully updated row is audited individually asupdate_product. Caps atMAX_BATCH_UPDATE=50. The input array param isitems(aligned withcategories_batch_update).Batch tools amplify writes per rate-limit token. A single
products_batch_update(orcategories_batch_update) of 50 rows costs one rate-limit token (60/min shared) while performing up to 50 DB writes. The rate limiter counts JSON-RPC requests, not sub-operations (RateLimiter.php:31-41,McpRequestHandler.php:50).*_statsanswer the whole audit in one query.categories_statsandproducts_statsrun a single conditional-SUMaggregate (Category/Product\Repository::seoStats) returningtotal,active,missing_meta_title,missing_meta_description,missing_both_meta,missing_description,incomplete_descriptionfor a scope — no pagination. "active" =published=1for categories,active=1 AND soft_delete=0for products. The "missing" predicates reuse the sharedContentPresenceSqlso a stat and the matchinghas_*filter cannot drift.Completeness is accurate per-row but approximate server-side (deliberate). The per-row
has_complete_description/description_lengthin list output is computed in PHP from the HTML-stripped clean text (Support\DescriptionMetrics). The server-sidehas_complete_descriptionfilter and theincomplete_descriptionstat use a faster rawCHAR_LENGTHSQL approximation (FilterByDescriptionCompleteness,ContentPresenceSql::complete/incomplete), which counts HTML markup — so a borderline row can classify differently between the two. Both sides share theAPP_MCP_DESCRIPTION_COMPLETE_MIN_CHARSthreshold (default 120). "incomplete" = present-but-short, disjoint from "missing" (empty/absent). The brief's categoryupdated_sincewas dropped (no timestamp column onshop_product_category).Category list filters mirror products; the default does not.
list_categoriesgainedhas_meta(+has_meta_title/has_meta_description),has_description,has_complete_description,parent_idandis_active(→published), routed via sentinel relations toFilterByContentPresence/FilterByDescriptionCompleteness(Category\Service::buildSpecifications).has_metauses the same rule as products. Unlikesearch_products(active-by-default),list_categoriesstill returns ALL categories when no filter is passed — a deliberate backward-compatibility choice (categories have no soft-delete, onlypublished).Category batch tools, and unified batch-update shape.
categories_batch_getmirrorsproducts_batch_get(max 100, WHERE IN, requested order +missing; no domain change — the genericFilteralready emitsIN). Bothcategories_batch_updateandproducts_batch_updatereuse their per-rowupdate*method (max 50, best-effort), share the input param nameitems, and return the samedata[]+ per-itemresults[]({id|index, status, error?}) +missing[]shape; an existence pre-check routes not-found ids tomissing[].Multi-token by design.
generate()inserts a new active row and does not revoke others (TokenService.php:29-43,TokenServiceTest.php:35).Scoped tool registration is structural. analytics-only ⇒ zero write tools; seo ⇒ the 20 catalog tools (16 pre-#713 + 4 product-tag tools); content ⇒ the 4 blog tools, and no scope lacking
contentcan reachcreate_article;get_shop_infounder every scope (McpServerFactory.php:157-172, asserted byServerFactoryTest::test_analytics_only_scope_registers_no_write_tools,::test_content_scope_registers_the_blog_tools_and_nothing_elseand::test_no_other_scope_can_reach_create_article).Legacy tokens = seo. NULL/blank scopes parses to
[seo]; an existing catalog token never silently gains analytics OR content — a token issued before #714 stays invisible to the blog tools until it is explicitly reissued withcontent(Scopes.php:50-60,ScopesTest.php:12-17, 42-50).Analytics is read-only + audited. Every analytics call is audited via
logRead()before delegating and never writes (AnalyticsTools.php:101,156,189;McpAuditLogger.php:70-93).Reporting conventions (CEO-confirmed). Reporting date =
shop_order.entry_datetime; ALL orders counted (phone/webignore NOT excluded —Service.php:20-22); no refunds metric; gross_revenue includes shipping. Cross-checkdocs/changelog/Changelog.4.117.md:31-33.Money-math (counter-intuitive columns). gross_revenue/order_total/avg_customer_value read
shop_order.total_vat(customer-paid grand total incl VAT + shipping); net_revenue/net_total readshop_order.total(net products excl VAT/shipping) (Repository.php:64-65, 201, 456;Service.php:543-544). Line-level net =SUM(subtotal / (1 + product_vat/100))(Repository.php:389, 579).orders_listPII stripping (defense-in-depth). SQL SELECT explicit allow-list, no PII columns (Repository.php:707-722); output row fixed allow-list (Service.php:536-552);customer_id='c_'.substr(hash_hmac('sha256', realId, secret),0,16)(opaque, stable, non-reversible; guest → null,Service.php:595-601); region coarse label only.customers_statsaggregate-only, zero PII — email used only as a SQL grouping key, never emitted (Service.php:417-482,ServiceTest.php:1248).price_historypromo caveat.on_promonever historically recoverable → always null,promo_history_available:false(PriceTracking/Service.php:70-85).Analytics ORDER BY escape invariant (#569). Every
order_by($bucketExpr, …)in the aggregation Repository MUST passescape=false, or CI3 compilesYEARWEEK(col ASC, 3) ASC(MySQL 1064) and thenum_rows()guard silently degrades week/month series to empty. All three call sites (src/Domains/Order/SalesAnalytics/Repository/Repository.php:303, 330, 594) supplyescape=false(Repository.php:26-35).MCP visibility exemption — analytics reads (#588). The analytics tools read products/categories through MCP's ProductTools and CategoryTools, which carry
private const VISIBILITY_EXEMPTIONS = ['categories']and route every read throughreadListRequest()/readProduct()(src/Mcp/Tools/ProductTools.php:53, 411, 426-429). This exemption is a correctness guard: without itupdateProduct()would diff against a visibility-scoped category set and silently delete ancestor-hidden pivot rows.A connector-created article has no categories or tags, and none can be assigned (#714).
Cms\Blog\Article\WriteService::create()/update()has no category- or tag-pivot branch — unlike the product writer'ssyncForProduct(), there is nothing here to call.create_article/update_articleaccept nocategory_ids/tag_idsparameter, and no other tool on the connector can assign either.CONTENT_INSTRUCTIONStells the LLM this explicitly, says that until it has categories and tags the standard storefront leaves it off the category and tag pages, and has the LLM send the operator to the admin blog screen to assign its categories, tags and publication date (McpServerFactory.php:97-100;src/Domains/Cms/Blog/Article/WriteService.php). Thecreate_articledescription spells out what a missing category and a missing publication date cost, as set out below, and adds that the admin form requires a title in every admin language (McpServerFactory.php:685;ecommercen/blog/controllers/Adv_blog_admin.php:440). A category is not what lists the article on the/blogindex, which has no category join (ecommercen/blog/models/Adv_blog_model.php::getBlogsList(),:15-30): a published article dated today or earlier is listed there whatever its categories, and its page opens with no related articles and no previous/next links (it answered HTTP 500 until Known Issue 18 was fixed). A missing category keeps the article off the category pages and out of other articles' previous/next and related lists (::getCategoryArticles(), join at:73;::getPreviousNext(),:158-222;::blogRelativeArticles(),:463-503), and missing tags keep it off the tag pages (::getTagArticles(), join at:124). With noblog_dateit is missing from every date-filtered listing (Known Issue 17).banner_imageis an unverified filename — MCP has no file transport (#714).create_articlerequiresbanner_image(blog.banner_image is NOT NULL, no default) but only trims and non-empty-checks it; nothing confirms the named file exists underfiles/blogs/, because the JSON-RPC tool-call protocol carries no file upload.CONTENT_INSTRUCTIONSand the tool's own input-schema description both instruct the LLM to reuse a real filename copied fromget_article'sbanner_imagefield or have the operator upload one in the admin blog screen first, but nothing server-side enforces this — a hallucinated filename creates an article with a broken image reference (BlogTools.php:192-233;McpServerFactory.php:688).Barcode lookups are exact by default (#1010).
search_productswithbarcodeuses thebarcodeExactfilter (an exactINmatch that can use KEY barcode onshop_product_barcodes) unlessbarcode_matchispartial, which uses thebarcodefilter as aLIKE %value%scan (ProductTools.php:113-114;src/Domains/Product/Product/Service.php:150-156;src/Domains/Product/Product/Repository/Specification/FilterByBarcode.php: exact:50-58,LIKE:60-69). Any otherbarcode_matchvalue throws aToolCallExceptionnaming the allowed values (ProductTools.php:84-89). Both match throughshop_product.id IN (subquery), so a product with several matching barcodes is one row. The active-only default still applies: an inactive product is not found by its barcode unlessis_activeis false orinclude_inactiveis true, and a soft-deleted one only wheninclude_inactiveis true (ProductTools.php:120-131).
Known Issues & Security Gaps
Token in URL path — access-log exposure. The secret credential is the URL path (
/mcp/c/<token>), so it appears in web-server and proxy access logs unless scrubbed. Mitigated in-app:McpAuditLoggermasks the URL (McpAuditLogger.php:53) and the admin UI shows only the masked form. The platform does not scrub proxy logs — operators must do so (documenteddocs/guides/mcp-connector.md:207-217).No per-tool authorization within a scope. Three scopes (seo, analytics, content) exist and an analytics-only token structurally cannot reach a write tool (
McpServerFactory.php:166-168,ServerFactoryTest::test_analytics_only_scope_registers_no_write_tools). Residual gap: within seo there is still no per-tool ACL — any seo token can call all 8 write tools across categories, products, product tags and brands,create_product_tagincluded; likewise a content token can call bothcreate_articleandupdate_articlewith no finer split. Blog authoring was given its own scope rather than folded intoseoprecisely to avoid widening every already-issued SEO token to include content creation (Scopes.php:21-27) — the distinction #352 (per-capability token scoping) exists to draw. Note the asymmetry that follows: #713 DID widen every existing seo token withcreate_product_tag, whereas #714 did not. Per-tool ACL itself remains deferred to post-MVP (OAuth 2.1, per-tool scopes, perdocs/guides/mcp-connector.md:218). Blast radius: all SEO/content of the eshop, or (content scope) all blog articles (src/Mcp/Tools/*).No cache invalidation after a write. The update tools call
WriteService::update()but nothing insrc/Mcp/invalidates storefront or product read caches. If reads are cached elsewhere, an MCP edit may not be reflected until the cache expires (src/Mcp/Tools/*).db_debugsuppression is per-request, instance-coupled.Mcp.php:38-41disablesdb_debugon theCI_DB_query_builderresolved from DI, relying onBaseRepositoryresolving the same instance. A different DB instance on the same request would retaindb_debugand could render a CI HTML error page that leaks SQL/schema. The flag is never re-enabled (acceptable — request ends after emit).Rate-limit counter is not atomic (read-then-write race).
RateLimiter::allow()reads the count then storescount + 1with no atomic increment or CAS (RateLimiter.php:34-41). Concurrent requests for the same token can allow the effective count to slightly exceed 60. This is a best-effort throttle, not a hard limit.McpAuditLoggersilently swallows failures.log()catches allThrowableand emits only alog_message('error', ...)line (McpAuditLogger.php:57-59). A persistent audit-DB failure means writes proceed unaudited with only a server log line.tests/Integration/Mcp/McpAuditLoggerTest.phppins thatlog()andlogRead()write their row, and thatlog()stores the masked URL (mcp/c/[redacted]) — it runs without theurlhelper loaded, as on a real MCP request (groupdatabase, so the PR pipeline does not run it); no test pins the never-throw behavior.HtmlSanitizeris regex-based, not a parser.HtmlSanitizer.php:24-30uses regexes to strip<script>,<iframe>,on*handlers, andjavascript:URLs. Regex HTML sanitizers can miss obfuscation patterns (data: URIs, SVG vectors, malformed/nested tags, style payloads). Weaker than HTMLPurifier (not bundled). Deliberate scope decision (HtmlSanitizer.php:7-14).update_product.category_idsis a full-replacement footgun. Passingcategory_idswithout first reading the current set overwrites all category assignments (ProductTools.php:327-334). The only guard is the tool description telling the LLM to callget_productfirst (McpServerFactory.php:510); no server-side guard prevents an accidental full-replacement shrink.Multi-token is by design; there is no per-shop token cap. Multiple non-revoked tokens may coexist intentionally. The only constraint is revocation:
revoked_at IS NULL(indexed) filters active rows. No DB-level cap on concurrency.MCP audit routes around
getPageInfo()deliberately.McpAuditLoggercallsadd()(inherited fromAdvAuditModel) directly rather thanstoreUserLog/storeRestLog, because those methods persist the request URI — which contains the plaintext token (McpAuditLogger.php:7-14). This is a deliberate token-safety measure, not a gap, but worth documenting here for future maintainers who might be tempted to consolidate audit paths.The on/off switch is guarded by key and, since #1054, by page. The switch is the registry setting
MCP_CONNECTOR.ENABLED(#824), which replaced the env-onlyAPP_MCP_CONNECTOR_ENABLEDthat epic #312 had deliberately kept out of the admin UI; Advisable now toggles it onsettings/only_advisablewithout a deploy.Adv_settings::only_advisable()writes it only when the session holdsAUTH_ROLE_ADVISABLE(Adv_settings.php:2471-2472). The constructor still admitsAUTH_ROLE_ADMIN(Adv_settings.php:23), but Resolved (#1054):_remap()now refuses every non-Advisable session with 401 on GET and POST foronly_advisable,xml_feeds_settings,ai_content_generation_promptsandai_content_generation_settings(Adv_settings.php:44-57, list:65-73), so an ADMIN session can no longer open the page or save its other toggles (Matomo, Farmakon, XML pricing, …), which was the residual gap left by #824. The key guard stays as defence in depth: a session without the Advisable role would still leave the switch exactly as it was — no write at all, and a missing row stays missing. Operationally, an environment that has not yet run the carry-over migration has no row, which reads as off: the connector stays closed untilphp migrator.php migratehas run (a standard deploy runs it at container start), and even then a registry cache populated before the migration keeps hiding the new row until it refreshes (see "Cache timing" under the On/off switch subsection). Pinned byAdvOnlyAdvisableMcpConnectorGuardTestandMcpConnectorEnabledTest.products_batch_getreturns inactive/soft-deleted products (by design). Unlikesearch_productswhich defaults to active+non-deleted,productsBatchGetapplies no active/visibility filter. A caller passing explicit ids will receive the full product data for inactive or soft-deleted products. This is intentional — ids are explicit and unambiguous — but distinguishes batch-get from search semantically (ProductTools.php:176-181, no active filter in:182-219).Batch-update partial success must be inspected per row. Both
*_batch_updatetools returndata[](applied rows, withchanged) alongsideresults[](per-item{id|index, status, error?}) andmissing[]; a partially-failing batch still returns HTTP/JSON-RPC success, so the LLM must readresults[]/missing[]to see which rows failed. No aggregate audit row is written for the batch as a whole — each successful sub-update is audited individually asupdate_product/update_category(McpAuditLogger:35-56).Scope fail-open to seo, unconditionally — not always an "upgrade" post-#714.
Scopes::parse()andpostedScopes()both fall back to[seo]whenever NONE of the requested CSV tokens match a known scope name — not only on fully empty input (Scopes.php:56-59,AdvMcpConnectorSettings.php:103-108). For an analytics-only token this is still a straight upgrade: read-only becomes write-capable. For a content-only token it is a scope swap, not a simple upgrade or downgrade: the token silently LOSES its intended blog-create capability and GAINS the unrelated seo catalog-write surface it was never granted. Either way the failure mode is "fails open to a write-capable scope" rather than "fails closed" — admin-only (a scopes CSV is set by this codebase, from checkbox input, not typed by hand), low blast radius. (No GH issue.)orders_listavailability depends on a secret. If neitherAPP_MCP_ANALYTICS_ID_SECRETnorencryption_keyis set,orders_listthrows and is unusable (Service.php:612-617); other analytics tools still work. Deliberate fail-closed, but an operational footgun on fresh installs.Analytics audit shares log()'s swallow-all behavior.
logRead()catches allThrowable→log_message('error',…)(McpAuditLogger.php:90-92), so a persistent audit-DB failure means reads proceed unaudited (same class as existing #6).A published article created without
blog_dateis missing from every date-filtered storefront listing (#714).create_articlesetsblog_dateonly when it is passed (BlogTools.php:272-274), and the column isDATETIME NULL DEFAULT NULL(database/migrations/20241024093212_change_blog_date_to_datetime.php:11), so an omitted date is stored as NULL — whereas the admin blog form saves today's date when its date field is empty (ecommercen/blog/controllers/Adv_blog_admin.php:334). The standard storefront's blog listings take only articles withis_published = 1 AND blog_date <= today, which a NULL date never satisfies: the blog index (ecommercen/blog/controllers/Adv_blog.php:121), the category and tag pages (:393,:610), the author page (:505-509), the previous/next links (:337), the RSS feed (:713), the footer list (ecommercen/core/Adv_front_controller.php:836-851), the sitemap (ecommercen/job/libraries/AdvGenerateSitemaps.php:318), storefront search (ecommercen/search/models/Adv_search_model.php:715, 746;Adv_search_model_v2.php:1004, 1035, 1058), the feed-module RSS (ecommercen/feeds/controllers/AdvBlogRSS.php:34) and the Doofinder feed (ecommercen/doofinder/models/AdvDoofinderModel.php:84). The REST read path has no date window —BlogArticle::storefrontRowScope()for the endpoint (src/Rest/Cms/Controllers/BlogArticle.php:233-252) andArticleVisibilityScopefor relations (src/Domains/Cms/Blog/Article/ArticleVisibilityScope.php:46-52) — so a headless storefront does receive the article. The connector cannot set the date afterwards (update_articlehas noblog_dateinput,McpServerFactory.php:702-717), and theblog_dateinput itself says only that omitting it leaves it unset (:696). The warning the model gets is at the tool level:CONTENT_INSTRUCTIONShas the model send the operator to the admin blog screen to assign a publication date along with the categories and tags, and thecreate_articledescription says that an article with no publication date is left out of every date-filtered listing (rule 38). Passingblog_dateis enough for those listings: since Known Issue 18 was fixed, their links open the article although it has no category. For an article already created without a date, the operator fix is to open it in the admin blog screen and assign it a category (the form requires one), a save that also stores a date. (GH issue #896.)On the standard storefront a published article with no category cannot be opened — its page returns HTTP 500 — and no article— Fixed (#900, pull request #350). Oncecreate_articlemakes has a category (#714).blogArticle()got past the draft check — for a published article, or a draft previewed from the back office; a guest asking for a draft still gets a 404 first (ecommercen/blog/controllers/Adv_blog.php:243-246) —Adv_blog_model::blogRelativeArticles()and::getPreviousNext()passed the article's category ids towhere_in()unchecked, and this repo's query builder throwsInvalidArgumentExceptionon an empty array. Both now return as soon as the category lookup comes back empty (ecommercen/blog/models/Adv_blog_model.php:478-482,:177-182), so a connector-created article's page opens, with no related articles and no previous/next links. The regression test istests/Legacy/Blog/AdvBlogModelEmptyCategoryGuardTest.php; the storefront behaviour is documented in CF-20 Blog. The article still has no category (rule 38), so it stays off the category pages and out of other articles' related and previous/next lists until an operator assigns one in the admin blog screen. The defect was in the legacy blog model, not insrc/Mcp/; headless storefronts on the REST API were never affected.A translation edit re-sends the full translation set as it was read at the start of the call.
mergedPayload()sends every stored language's row, the target row's untouched columns included, with the values the tool read before diffing (TranslationMerger.php:66-81), and the upsert writes every column a row carries (BaseMuiWriteRepository.php:62-72). A change another writer saves to the same entity's translations between the tool's read and its write — in another language, or in another column of the target language — is therefore overwritten with the value read. A row carrying only the changed columns would not do this (rule 2). The window is a single tool call, so this is a narrow lost-update race rather than a routine loss. (No GH issue.)A connector-created draft that names an author is listed publicly on that author's storefront page (#714).— Fixed (pull request #349).create_articlemakes a DRAFT unlessis_published: trueis passed, which the connector presents as the safe default (BlogTools.php:196-198;McpServerFactory.php:685, 695), and it storesblog_author_idwhen one is given (BlogTools.php:275-277).blogAuthor()used to filter on the author alone, andgetBlogsList()adds nothing (ecommercen/blog/models/Adv_blog_model.php:15-30). The view renders every row it gets with its title, banner, teaser and link (application/views/main/layouts/blog/blog_author.php:54-90), so the draft was public there before anyone published it, and future-dated and NULL-dated articles were listed the same way. The author page now applies the condition the other listings use,is_published = 1 AND blog_date <= today(ecommercen/blog/controllers/Adv_blog.php:505-509). Drafts and future-dated articles stay off it, admin-created ones included, and so do NULL-dated ones (Known Issue 17). The regression test istests/Legacy/Blog/AdvBlogAuthorPublicationWindowTest.php; the storefront behaviour is documented in CF-20 Blog. (GH issue #899.)
Tests
All under tests/Unit/Mcp/ and tests/Integration/Mcp/ (pure Unit, mocked services; Integration scope-testing), except the on/off-switch tests (#824), which live elsewhere — see "On/off switch (#824)" below. Smoke test under tests/smoke/mcp/ (manual CLI, outside PHPUnit).
Auth & Scopes
| File | Lines | Covers |
|---|---|---|
tests/Unit/Mcp/Auth/ScopesTest.php | 78 | NULL/blank → [seo]; trim/lowercase/canonical order incl. content; content appended last so existing token CSVs are byte-unchanged; a legacy/seo-only token never gains content; unknown dropped → fallback; format() canonical CSV incl. content (extended for #714) |
tests/Unit/Mcp/Auth/TokenServiceTest.php | 138 | generate() persists hash/hint/label/scopes, never plaintext, never revokes; rotate() revokes+regenerates same label/scopes; rotate() unknown → null; list() parses scopes |
tests/Unit/Mcp/Auth/TokenGuardTest.php | 108 | (updated) hash lookup path |
HTTP Pipeline & Server
| File | Lines | Covers |
|---|---|---|
tests/Unit/Mcp/Http/McpRequestHandlerTest.php | 306 | Invalid → 401 (server never built); rate-limited → 429 + Retry-After; happy path → 200 JSON-RPC with real Mcp\Server + FileSessionStore; #861 protocol-version tests: initialize passes the matching ProtocolVersion to the factory; an unsupported or malformed version passes null; a non-initialize method, invalid JSON and a batch body pass null; a consumed non-seekable body is rebuilt so the SDK still reads it |
tests/Unit/Mcp/Http/RateLimiterTest.php | 67 | Allow up to 60 then block; per-identifier independence; limit/window getters |
tests/Unit/Mcp/Server/CacheSessionStoreTest.php | 141 | Write/read round-trip; exists/destroy; non-string → false; TTL passthrough; all-fail → false (graceful degrade, #337) |
tests/Integration/Mcp/ServerFactoryTest.php | 268 | Also test_initialize_echoes_the_requested_protocol_version (data provider, all four versions) and test_initialize_without_a_version_replies_with_the_sdk_latest (#861). Scope isolation over the real DI container + a real Mcp\Server: seo registers the 8 WRITE_TOOLS (incl. create_product_tag, update_product_tag, #713) + no analytics/blog tools; content registers the 4 BLOG_TOOLS (incl. create_article) + nothing else (#714); no scope combination lacking content can reach create_article; analytics-only registers NO write tool; seo+analytics = union; all three = union. This file runs in NO PHPUnit testsuite (#526, verified against phpunit.xml.dist's four <testsuite> blocks, none of which lists tests/Integration/Mcp) — none of these assertions execute under composer test; treat them as documentation of intent, not live-verified behavior. |
SEO Tools
| File | Lines | Covers |
|---|---|---|
tests/Unit/Mcp/Support/HtmlSanitizerTest.php | 62 | Strips script/handlers/js-urls; keeps img/tables; null passthrough |
tests/Unit/Mcp/Support/LogMessageLoggerTest.php | 61 | Prefix; exception folding; custom prefix; non-throwable ignored; no-op without log_message |
tests/Unit/Mcp/Support/DescriptionMetricsTest.php | 67 | HTML-stripped clean-text length computation; completeness threshold; accuracy vs raw-length server-side approximation |
tests/Unit/Mcp/Support/ToolResultTest.php | 132 | Hard meta-length limits: absent fields and values exactly at the limit are accepted and passed through untouched (never trimmed); an over-length meta_title/meta_description throws ToolCallException naming the actual + permitted length; both fields over limit are reported in one error; char-count not bytes (multibyte Greek accepted at the limit, rejected over it); constants pinned to the platform SEO convention (65/150) |
tests/Unit/Mcp/Support/TranslationMergerTest.php | 142 | Merges only target lang; non-editable cols survive (incl. vendor fixture, #315); strips id/fk/repository; missing-lang null/throws |
tests/Unit/Mcp/Tools/BlogToolsTest.php | 742 | 41 tests (#714). List: the title filter maps to the real blog_mui.title column as Partial (the regression guard on #579's fix) and an empty title is dropped rather than forwarded; filters route to the right domain keys; drafts+published returned by default; date range requires both bounds (one-sided/malformed rejected); per_page clamped to 20; per-locale sort suffixing; -id default sort vs. an explicit sort overriding it; unknown sort key rejected; list projection carries no body, only description_length. Get: not-found names list_articles; default-lang resolution. Update: not-found throws; happy path audits once; no_changes skips write+audit; a publish-only change (root is_published) writes once and audits once WITHOUT reporting no_changes; unpublishing is a real change; the flag already at the target value is no_changes; mergedPayload() writes every language's row, not only the target (incl. the untouched row's slug); empty title rejected; over-length meta_description hard-rejects and writes nothing (accepted exactly at the limit); domain ValidationException → ToolCallException. Create: writes the translation row in the resolved language; lands as a draft unless is_published:true; audits once; HtmlSanitizer invoked explicitly on description and small_description; over-length meta_title/meta_description rejected via ToolResult::enforceLengths() before any write; blank banner_image, blank title, and a punctuation/emoji-only title (empty slug) all rejected before the domain call; a malformed blog_date rejected; a null WriteService::create() return (swallowed transaction failure) maps to ToolCallException; domain ValidationException → ToolCallException |
tests/Unit/Mcp/Tools/CategoryToolsTest.php | 396 | Not-found; default-lang; happy path audits once; no_changes skips write + audit; ValidationException → ToolCallException; empty name rejected |
tests/Unit/Mcp/Tools/ProductToolsTest.php | 804 | Not-found; title change audits once; unknown brand throws; no_changes skips; content ValidationException → ToolCallException; active-scope default; include_inactive; has_meta routing; is_active override; vendor_id alias; updated_since normalization; invalid date; per_page clamp; read-only core fields; batch_get ordering/missing/empty/cap; batch_update best-effort/cap; the ten barcode tests (:671-803, #1010): exact by default, partial, blank is no filter, invalid barcode_match throws, active-only default and include_inactive, the barcodes relation is loaded without a new visibility exemption, and the barcodes projection in search rows and get_product |
tests/Unit/Mcp/Tools/ShopToolsTest.php | 51 | Default lang + languages; degrades to empty name when registry absent (#332) |
tests/Unit/Mcp/Tools/VendorToolsTest.php | 133 | Not-found; happy path audits once; no_changes skips |
Analytics Tools
| File | Lines | Covers |
|---|---|---|
tests/Unit/Mcp/Tools/AnalyticsToolsTest.php | 814 | 56 tests — all 7 tools: enum/date validation → ToolCallException, id caps, limit clamps, defaults, audits-once, domain-exception → ToolCallException |
tests/Unit/Domains/Order/SalesAnalytics/AnalyticsRequestTest.php | 119 | Strict date parse, from≤to, ≤366-day span |
tests/Unit/Domains/Order/SalesAnalytics/BucketTest.php | 97 | Enum guard + SQL expressions |
tests/Unit/Domains/Order/SalesAnalytics/SaleStatusesTest.php | 124 | Default set; registry override; blank fallback |
tests/Unit/Domains/Order/SalesAnalytics/ServiceTest.php | 1470 | Envelope/cache-key; summary + compare windows; timeseries merge; breakdown sort/limit/delta; product_sales margin/avg guards; orders_list PII allow-list, opaque stable id, guest→null, no-secret throws, cursor round-trip; customers_stats aggregates |
tests/Unit/Domains/Product/PriceTracking/ServiceTest.php | 292 | (extended) priceHistory() |
On/off switch (#824)
| File | Lines | Covers |
|---|---|---|
tests/Unit/Helpers/McpConnectorEnabledTest.php | 162 | isMcpConnectorEnabled() reads only MCP_CONNECTOR.ENABLED: '1' on; '0', '' and no row off; the retired APP_MCP_CONNECTOR_ENABLED set to 'true' cannot switch it on; the helper loads the registry library itself. Each test runs in a separate process, because the registry_helper.php functions cannot be redefined in-process |
tests/Legacy/Settings/AdvOnlyAdvisableMcpConnectorGuardTest.php | 346 | Adv_settings::only_advisable() over a stubbed registry: an Advisable session stores the posted state as an int (on; off via the unposted checkbox; on where no row exists yet; Advisable who is also an admin); a session without AUTH_ROLE_ADVISABLE (admin, developer, admin + developer) never writes the key — a missing row stays missing — while the rest of the page (XML_FEEDS.CUSTOM_PRICE_ENABLED) still saves; an Advisable write also clears the whole pscache (Adv_settings.php:2387), and a session that cannot write the switch clears nothing |
tests/Unit/Migrations/AddMcpConnectorEnabledRegistryKeyTest.php | 102 | The carry-over migration's up(), run against a mocked adapter for each raw APP_MCP_CONNECTOR_ENABLED value. It writes the flag the runtime env() resolves to: true/(true)/1 ⇒ 1; false/(false)/0/empty/absent and the null/empty keywords, bare or in parentheses, ⇒ 0; a value wrapped in matching quotes is not re-parsed, so "false" ⇒ 1 and '0' ⇒ 0, and mismatched quotes are not stripped. The unquoted false row is the one a naive (bool) cast gets wrong. The WHERE NOT EXISTS guard is not exercised here |
tests/Legacy/Settings/AdvOnlyAdvisableCustomPriceResetTest.php | 385 | Existing #592 spec, harness adjusted for #824: it now loads auth_helper.php and injects an Advisable session, because the save block calls allowRole(), and it stubs pscache because the save clears the cache |
Fixtures: tests/data/fixtures/mcp/vendor_translations.json.
Smoke test (tests/smoke/mcp/{run.php,worker.php,README.md}): the #313 dependency spike proving mcp/sdk ~0.6.0 round-trips initialize → tools/list across separate PHP processes via FileSessionStore. README documents that the bare SDK answers with its built-in latest protocolVersion (the production connector now echoes a supported requested version, see Protocol Surface) and that default middleware (CORS, DNS-rebinding, protocol-version) is disabled via middleware: [] (McpRequestHandler.php:69-73).
Coverage gaps:
McpAuditLoggerhas only a database-group integration test (tests/Integration/Mcp/McpAuditLoggerTest.php, row written bylog()/logRead(), and the masked URL oflog()) — the never-throw behavior and the masked URL oflogRead()are unverified by PHPUnit.- No test for
Mcp::connector(flag gate,db_debugsuppression) or forAdvMcpConnectorSettings::guardWrite()— the gate's decision,isMcpConnectorEnabled(), is pinned byMcpConnectorEnabledTest, but nothing asserts that the controllers call it; only the smoke harness exercises the SDK end-to-end. - No test for
ArrayListInput. - No integration test against a real DB for the full tool →
WriteService→*_muiwrite path. LanguageResolverhas no dedicated unit test.- No test for
PsrBridge. - No DB-integration test of the analytics SQL against a real
shop_order/shop_order_basket(Service tests mock the Repository); the money-math column mapping is verified only against mocked rows. - The #824 carry-over migration's
INSERT … WHERE NOT EXISTSguard runs under no PHPUnit test:AddMcpConnectorEnabledRegistryKeyTestmocks the adapter, so it pins the$_ENVread, the mapping and the SQL shape, but not that an existing row is left alone.
Related Flows
- SY-04 Price Tracking — canonical home for the
price_trackingschema +PriceTracking\Service/Repository, reused by theprice_historyanalytics tool - SY-23 MUI Translation Pattern — canonical home for the
_muiupsert contract (upsertForEntity()) that every connector translation update goes through (the two create tools insert throughinsertForEntity()instead) - SY-29 Deployment Architecture — canonical source for the K8s Redis session topology (session Redis vs L2 cache Redis, KEDA multi-pod routing) that the MCP session store depends on (
SY-29:269, 283) - AD-02 Product Management (Admin) — canonical home for the
shop_products/shop_products_muischema;Product\WriteServiceis the domain service called byupdate_productandupdate_product_content; also read by analytics for product pricing/vendor - AD-03 Order Management (Admin) — canonical home for the
shop_order/shop_order_basketschema read by theSalesAnalytics\Serviceaggregates (sales_summary, sales_timeseries, sales_breakdown, orders_list, product_sales, customers_stats) - AD-05 Category Management — canonical home for the
shop_category/shop_category_muischema;Category\WriteServiceis the domain service called byupdate_category - AD-19 Vendor Management — canonical home for the
shop_vendor/shop_vendor_muischema;Vendor\WriteServiceis the domain service called byupdate_brand - AD-13 Admin Settings & Configuration — canonical home for the
settings/only_advisablepage and the registry; hosts theMCP_CONNECTOR.ENABLEDon/off switch (#824), guarded to Advisable sessions by key docs/guides/mcp-connector.md— operator and developer guide; curl JSON-RPC acceptance collection; security operational notes (proxy log scrubbing, token rotation); post-MVP OAuth 2.1 scopes roadmap; analytics tool parameter examplesdocs/guides/mcp-connector-onboarding-el.md— Greek customer onboarding guide with screenshots (shipped in 4.107.3, #321)