Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Update plans around MCP and action ownership
Damian Legawiec0cd7fcf38f55
diff --git a/docs/plans/6.0-action-actors.md b/docs/plans/6.0-action-actors.mdnew file mode 100644index 0000000000..7a7ad48e52--- /dev/null+++ b/docs/plans/6.0-action-actors.md@@ -0,0 +1,233 @@+# Action Actors++**Status:** Draft — design finalized 2026-09-16, nothing built+**Target:** Spree 6.0 — before `6.0-mcp-server.md`, which depends on it+**Depends on:** `5.5-admin-api-key-scopes.md` (shipped — the API key is the second kind of actor), `6.0-service-workflows.md` (workflows already take the actor as a keyword), `6.0-platform-auth.md` (the admin user class the columns point at today)+**Author:** Damian Legawiec (design driven with Claude)+**Last updated:** 2026-09-16+**Tracking:** Linear V-3646 · GitHub spree/spree#14658++## Summary++Every record that remembers who performed an action on it — who cancelled or+approved an order, who created a return, who received a stock transfer —+points at the admin user class and nothing else. A write made with a secret+API key therefore records nobody: the WMS connector that receives stock, the+integration that approves returns, and soon every MCP client, all leave+`canceler`, `approver`, `created_by` and their siblings empty. This plan makes+those associations polymorphic so an API key is a valid actor, adds the+`current_actor` the Admin API passes to workflows instead of the user alone,+backfills existing rows, and exposes the actor's kind on the wire. The 6.0+cut covers the order operations — 8 associations on 6 tables — because those+are the paths the MCP server and warehouse connectors hit first; the remaining+13 follow in 6.1 through the same macro. It is a schema change first, which is+why it ships before the MCP server rather than inside it. Personal user-bound keys are not built: the industry is moving+attribution to apps and credentials, and staff identity for machine clients+arrives with OAuth in a later release.++## Key Decisions (do not deviate without discussion)++- **The actor of a key-authenticated write is the API key (2026-09-16).**+ Not a personal key, not a service user. The key is what gets named, scoped+ and revoked, so it is the stable thing to attribute to; when an App model+ arrives a key can `belongs_to :app` and displays through it, while the row+ on the order keeps pointing at the key. Rejected: user-bound personal keys+ (platforms are retiring them, and a WMS connector is not a person) and+ deferring attribution to OAuth (leaves every key write unattributed through+ 6.0).+- **Two actor kinds at 6.0, registered, not open-ended (2026-09-16).**+ `Spree.actor_classes` holds the admin user class and `Spree::ApiKey`; the+ polymorphic type column is validated against it. Extensions register an+ App or a bot class the same way they register providers. An unregistered+ class is refused at write time, so a `_type` column can never hold a+ customer or an arbitrary model.+- **6.0 converts the order operations; the rest converts in 6.1+ (2026-09-16).** Orders (`created_by`, `approver`, `canceler`), refunds+ (`refunder`), returns, exchanges and claims (`created_by`) and stock+ receipts (`received_by`): 8 columns on 6 tables, the writes an MCP client or+ a warehouse connector performs. Purchase orders, stock transfers, gift cards+ and batches, store credits, tax exemption certificates, product and seller+ requirement submissions and data requests (13 columns on 9 tables) convert+ in 6.1 with a second migration and the same backfill task. Accepted+ trade-off: for one release the same idea is recorded two ways, and a+ key-created purchase order still records nobody. Rejected: all 21 at once+ (a wider migration than the 6.0 timeline wants) and all 24 including+ ownership (a key cannot open the dashboard to see "its" exports).+- **Ownership associations are not actors and stay user-only+ (2026-09-16).** `Import#user`, `Export#user` and `SavedReport#user` gate+ visibility ("my exports"), they do not record an action. A key-created+ export has no owner, as today.+- **Existing rows keep working before the backfill runs (2026-09-16).** A+ polymorphic association with a `_type` of `nil` answers `nil` in Rails, so+ the reader falls back to the admin user class while the type column is+ empty and warns through `Spree::Deprecation`. The backfill rake task makes+ the fallback unnecessary; the fallback is removed in 6.1.+- **The wire exposes the kind as a shorthand next to the id+ (2026-09-16).** `canceler_id` stays a prefixed id (`admin_…` or `key_…`);+ a sibling `canceler_type` carries `admin_user` or `api_key` through+ `Spree::Base.polymorphic_api_type`, the house pattern for polymorphic+ columns. No nested actor object: the dashboard resolves a name from the id+ when it needs one, and the payload of every order does not grow by an+ object per actor.+- **Workflows are not touched (2026-09-16).** They already take the actor+ as a keyword (`canceler:`, `approver:`, `created_by:`, `reviewer:`) typed+ `[Object, nil]`, and assign it to the association. Only the callers change:+ the Admin API passes `current_actor` where it passed the user.+- **Attribution and audit are different things (2026-09-16).** This plan+ answers "who". "Through which surface" (dashboard, REST, MCP) is an event+ the MCP adapter publishes per mutating tool call, defined in+ `6.0-mcp-server.md`; no `_via` columns here.++## Design Details++### The `Spree::Actor` contract and the `acted_by` macro++```ruby+# spree/core/app/models/concerns/spree/actor.rb — included in the admin user+# class and Spree::ApiKey; an extension's App class includes it too.+module Spree::Actor+ def actor_label # what a timeline shows: full name / email, or the key's name+ def actor_kind # 'admin_user' | 'api_key' | … — polymorphic_api_type of the class+end++# spree/core/app/models/concerns/spree/acted_by.rb+class Spree::Order < Spree.base_class+ include Spree::ActedBy+ acted_by :created_by, :approver, :canceler+end+```++`acted_by :name` declares `belongs_to :name, polymorphic: true, optional: true`,+validates `name_type` against `Spree.actor_classes` when present, and defines+the transitional reader: when `name_type` is `nil` and `name_id` is present,+resolve through the admin user class and warn once per process. The+association names, readers and writers do not change, so every workflow that+does `order.canceler = canceler` keeps working with either kind of actor. The+macro replaces 8 `belongs_to … class_name: Spree.admin_user_class` lines at+6.0 and the remaining 13 at 6.1.++### What converts++**6.0 — order operations**++| Table | Associations |+|---|---|+| `spree_orders` | `created_by`, `approver`, `canceler` |+| `spree_refunds` | `refunder` |+| `spree_returns` | `created_by` |+| `spree_exchanges` | `created_by` |+| `spree_claims` | `created_by` |+| `spree_stock_receipts` | `received_by` |++**6.1 — the rest, same macro, second migration**++| Table | Associations |+|---|---|+| `spree_purchase_orders` | `created_by` |+| `spree_stock_transfers` | `created_by` |+| `spree_gift_cards` | `created_by` |+| `spree_gift_card_batches` | `created_by` |+| `spree_store_credits` | `created_by` |+| `spree_tax_exemption_certificates` | `verified_by` |+| `spree_product_submissions` | `submitted_by`, `reviewed_by` |+| `spree_seller_requirement_submissions` | `submitted_by`, `reviewed_by` |+| `spree_data_requests` | `requested_by` |++Never converted: `spree_imports.user`, `spree_exports.user`,+`spree_saved_reports.user` (ownership), and `spree_api_keys.created_by` /+`revoked_by` (already polymorphic).++### Migration++One migration, `OrderOperationActorsPolymorphic`, targeting `[8.1]`: for+each 6.0 association above, `add_column :<table>, :<name>_type, :string` (nullable, no+default — the type is data, filled by the backfill) and+`add_index :<table>, [:<name>_type, :<name>_id]`. The existing `_id` indexes+stay. No foreign keys, per the migration rules.++### Backfill++`spree:upgrade:backfill_actor_types` sets `<name>_type` to+`Spree.admin_user_class.name` wherever `<name>_id` is present and `_type` is+`nil`, table by table with `update_all` in batches, over whatever+associations are declared with `acted_by` at the time, so the 6.1 conversion+reuses it unchanged. Idempotent. Listed in the 6.0 upgrade guide after+migrations; the transitional reader means nothing+breaks if an installation runs it late.++### The Admin API passes `current_actor`++`Spree::Api::V3::Admin::BaseController#current_actor` answers the signed-in+admin for a JWT request and `current_api_key` for a key request. The ten+call sites that pass `try_spree_current_user` as an actor keyword+(`canceler:`, `approver:`, `created_by:`, `reviewer:`, `refunder:`, `user:`)+pass `current_actor` instead. Controllers that assign an actor directly+(`@resource.approved_by(try_spree_current_user)`) do the same. A workflow that+needs a *person* specifically — none does today — would check+`actor.is_a?(Spree.admin_user_class)` itself.++### Serializers++Every admin serializer exposing `<name>_id` gains `<name>_type`+(`typelize … enum_type_name: 'ActorKind'`, an open list because extensions+register kinds). The id stays the actor's prefixed id, so an `api_key` actor+reads `key_…`. Store serializers expose no actors and are unchanged. The+`Spree::Api::V3::Admin::ApiKeySerializer` already shows `created_by_email`;+it is left alone.++### Dashboard++Order, return and claim pages that show "cancelled by" or "created by" render+the actor's label from the id: a person's name for `admin_user`, the key's+name with a key icon for `api_key`. Strings through i18next in every locale.+No new screens.++### Events++Event payloads carrying actor ids already use prefixed ids, so an+`api_key` actor is visible to subscribers as `key_…` with no payload change.++## Migration Path++1. **Core:** `Spree::Actor`, `Spree::ActedBy`, `Spree.actor_classes`, the+ macro applied to the 8 order-operation associations, the migration, the+ backfill task,+ model specs for the type validation and the transitional reader.+2. **API:** `current_actor`, the ten call-site changes, `<name>_type` on the+ serializers, regenerated types and OpenAPI, controller specs asserting a+ key-authenticated cancel records the key.+3. **Dashboard:** actor labels where actors are shown.+4. **Docs:** the 6.0 upgrade guide gains the backfill step; the Admin API+ docs note that `*_id` actors may be keys and what `*_type` says.+5. `6.0-mcp-server.md` then injects `context.actor` (user or key) into+ workflow principal parameters with no further change.+6. **6.1:** the macro on the remaining 13 associations, one migration, the+ same backfill task, the serializer fields, and removal of the+ transitional reader.++## Constraints on Current Work++- **A new "who did this" association is declared with `acted_by`**, never+ with `belongs_to … class_name: Spree.admin_user_class`. Ownership+ associations that gate visibility keep the plain form.+- **Controllers pass `current_actor` to workflows**, not+ `try_spree_current_user`, for any actor keyword.+- **Workflow principal parameters stay typed `[Object, nil]`** and are+ assigned, not inspected; a workflow that must refuse non-human actors says+ so explicitly and documents why.+- **A new actor kind registers in `Spree.actor_classes`** in the same PR that+ introduces the class.++## Open Questions++Nothing blocks implementation. Deferred by decision, not by uncertainty: the+13 remaining associations (6.1, step 6), and OAuth-issued identity for+machine clients, which will resolve a token to one of the two actor kinds+defined here (`6.0-mcp-server.md`, OAuth lane).++## References++- `docs/plans/6.0-mcp-server.md` — the consumer; its principal injection depends on this plan+- `docs/plans/5.5-admin-api-key-scopes.md` — the API key model and its already-polymorphic `created_by`+- `docs/plans/6.0-service-workflows.md` — actor keywords on workflows+- Precedents for attributing to apps and credentials rather than people: Shopify order timeline "by app", Stripe request attribution to keys and OAuth apps, GitHub's move from classic personal tokens to app installationsdiff --git a/docs/plans/6.0-mcp-server.md b/docs/plans/6.0-mcp-server.mdnew file mode 100644index 0000000000..83c0c9273e--- /dev/null+++ b/docs/plans/6.0-mcp-server.md@@ -0,0 +1,688 @@+# Admin MCP Server++**Status:** Draft — design finalized 2026-09-16, nothing built+**Target:** Spree 6.0+**Depends on:** `6.0-action-actors.md` (ships first — the API key becomes a valid actor, so a workflow run over MCP records who did it), `5.5-admin-api-cli.md` (shipped — the CLI-first precondition this plan waited on), `5.5-admin-api-key-scopes.md` (shipped — secret keys + scopes are the credential), `6.0-admin-rbac.md` (the permission catalog gates every tool), `6.0-analytics-semantic-layer.md` (the reporting registry feeds the reporting tools), `6.0-service-workflows.md` (writes execute through workflows), `6.0-dashboard-assistant.md` (moves onto the registry defined here)+**Author:** Damian Legawiec (design driven with Claude)+**Last updated:** 2026-09-16+**Tracking:** Linear V-3645 · GitHub spree/spree#14656++## Summary++A Model Context Protocol server for the back office, so any MCP client — Claude+Code, Claude Desktop and claude.ai connectors, Cursor, in-house agents — can+merchandise the catalog, query the reporting engine and manage store setup+(markets, channels, delivery, payments) in plain language, under the same+tenancy and permission rules as the Admin API. The server is a thin protocol+adapter over a Spree-owned **agent-tool registry** that lives in `spree_core`;+the dashboard chat assistant (`6.0-dashboard-assistant.md`, unmerged) becomes+the second adapter over that same registry once this ships. The order is+deliberate: MCP first, assistant second. The registry is not a mirror of the+Admin API: generic read tools driven by the admin controllers and the OpenAPI+spec, reporting tools driven by the reporting registry, and one write tool per+exposed workflow with its schema derived from the workflow's own signature —+because every back-office write already is a workflow.++## Key Decisions (do not deviate without discussion)++- **MCP ships first, the assistant follows (2026-09-15).** The CLI plan's+ ordering (CLI → MCP → assistant) is now the sequence: `spree api` has+ shipped, so the "no MCP before the CLI" constraint is satisfied. The+ assistant branch already holds a registry designed for exactly this reuse;+ this plan extracts that registry into core, ships the MCP adapter on it, and+ the assistant rebases onto it. The assistant plan's "No MCP in 6.0" decision+ is superseded by this plan (see `decisions.md`, 2026-09-15).+- **The registry lives in `spree_core`, no new gem (2026-09-15).** It is a+ contract like `Spree.integrations`, `Spree.tax_providers` and+ `Spree.reporting`, and core is where Spree keeps contracts: an EasyPost or+ Stripe gem can register a tool without depending on either the MCP or the+ assistant gem. A registry of names, schemas and permission keys carries no+ LLM dependency, so the assistant plan's rule that core takes none still+ holds. Names: `Spree::AgentTool` (base class), `Spree.agent_tools`+ (registry), `Spree::AgentTools::*` (built-ins). Not `spree_ai` or+ `spree_agents`: nothing intelligent runs in the registry, and a name that+ promised otherwise would claim the adapters' job.+- **Never one tool per endpoint; tools come from registries (2026-09-15).**+ The Admin API has ninety-five controllers; wrapping them would produce two+ hundred plus tools, and the CLI plan already priced that (a ninety-three-tool+ server costs roughly fifty-five thousand tokens of context; some clients cap+ at forty). The catalog is four tiers — generic reads, reporting, workflow+ tools, generic record writes — and its *parameters* come from registries+ Spree already maintains, never from hand-written lists (see Design Details).+- **Workflows are the write tools (2026-09-16).** Reviewing the orders and+ products controllers settled the shape of the write tier: every back-office+ write already goes through a workflow registered in `Spree::Dependencies`+ (57 distinct workflows called from admin controllers on 2026-09-16), the+ base controller calls the declared `create_workflow` / `update_workflow`+ rather than saving records, and each workflow's `perform` keyword signature+ plus its YARD `@param` block is a machine-readable contract. So each exposed+ workflow becomes one MCP tool with a derived schema, and the hand-written+ task tools of the first draft are gone — each was a thin wrapper over one+ workflow. Rejected: a single `run_workflow` tool (every write becomes two or+ three calls and the client can only confirm "run_workflow", not the action)+ and a hybrid of first-class families plus a generic tail (two conventions+ that drift).+- **Exposure is an allowlist in core, keyed by dependency key (2026-09-16).**+ `Spree.agent_tools.expose_workflows(order_cancel_workflow: 'write_orders', …)`+ lives in `spree_core`; workflows themselves stay untouched. Keying by the+ dependency key means a host app that swaps `Spree.order_cancel_workflow`+ for its own class keeps the tool, with the schema read from the+ replacement's signature. Internal workflows (recalculation, cart merge,+ webhook handling, payout sweeps) are simply not listed. A contract spec+ keeps the list honest against the controllers, which remain the reference+ wiring for how a request becomes workflow keywords. Rejected: a declaration+ on each workflow class (scatters the catalog across 57 files) and a+ generated manifest from controller source (a second `admin.yaml` to+ regenerate).+- **Workflows only; Tier 1 services are promoted, not adapted (2026-09-16).**+ Seventeen services the admin controllers still call (order create and+ update, fees, discounts, addresses, stock levels, store credits) are not+ exposed. Order editing reaches agents as those paths become workflows — the+ 6.1 order-change substrate covers most of them — never through a second+ adapter for `call` signatures.+- **Secret API keys with scopes are the credential; OAuth is a later lane+ (2026-09-15).** The server authenticates with the same `sk_` key and+ `X-Spree-API-Key` header as the Admin API and offers only the tools the+ key's scopes permit. Consumer connectors that require OAuth 2.1 (claude.ai+ hosted connectors, ChatGPT) wait on an authorization-server capability Spree+ does not have; `6.0-platform-auth` phase 7 is OIDC *login*, which is not it.+ The transport, tool catalog and scope filtering are unchanged when OAuth+ arrives, so nothing here is throwaway.+- **The key travels as a header, in either of two forms (2026-09-16).**+ `X-Spree-API-Key: sk_…`, the Admin API's header, or+ `Authorization: Bearer sk_…`, because several MCP clients offer only a+ bearer-token field and no custom header. The `sk_` prefix keeps it+ unambiguous against the JWTs the Admin API accepts in the same header; the+ MCP controller refuses a JWT outright. No login, redirect or refresh: the+ key is the whole credential, and revocation in the dashboard is how it+ ends.+- **Writes are scope-gated on the server and confirmed by the client+ (2026-09-15).** MCP has no approval card. A tool marked mutating is offered+ only to a key holding the matching `write_*` scope, and every mutating tool+ returns a one-line human summary of what it did so the client's own+ confirmation prompt (Claude Code and Claude Desktop ask before running a+ tool) has something to show. The assistant's server-side approval gate+ remains an assistant concern, built on the same `mutating` flag.+- **Tools execute through workflows, never by writing models (2026-09-15).**+ A workflow tool calls the registered workflow; a generic record write exists+ only for a resource whose controller declares no workflow and takes the+ exact path the controller takes for it. Validations, hooks, events and+ webhooks fire exactly as from the dashboard or the API. The MCP server never+ calls its own HTTP endpoints.+- **Official `mcp` Ruby gem, served by a Spree controller, not by the gem's+ Rack transport (2026-09-15; transport detail corrected 2026-09-16).** The+ gem is maintained by the protocol's working group and has supported the+ stateless 2026-07-28 revision since 1.2.0 (current 1.5.1). Its Rack+ transport takes one pre-built server for every request, which cannot carry+ a per-request principal, so the endpoint is an ordinary admin API+ controller: it authenticates the secret key with the existing concern,+ builds an `MCP::Server` for that key (its tools, its context) and answers+ with `handle_json`. Plain JSON responses, stateless, no server-to-client+ stream. No separate process to deploy; tenancy, scoping, rate limiting and+ security headers are the Admin API's, and the whole server is exercisable+ in a spec by handing it a JSON-RPC string.+- **Optional gem `spree_mcp` under `spree/mcp` (2026-09-15).** Beside+ `opentelemetry` and `dashboard`, the precedent for optional top-level+ engines. `spree_api` does not take the `mcp` dependency; installs that do+ not want an MCP endpoint do not get one.+- **Generic record writes only where no workflow exists (2026-09-16;+ narrows the 2026-09-15 decision).** `create_resource` / `update_resource` /+ `delete_resource` over the resource map, with writable schemas read from the+ generated `admin.yaml`, cover store, market, channel, delivery, payment and+ tax setup — resources whose controllers save the record directly. A+ resource with a create or update workflow refuses the generic write and+ names the workflow tool instead, so there is exactly one way to write each+ thing. No task tools at 6.0; a composed tool is added only when usage shows+ a job spanning several workflows that the model fails to sequence.+- **No `spree mcp` command in `@spree/cli` at 6.0 (2026-09-15).** The mounted+ Streamable HTTP endpoint serves every current client directly with a key in+ the client config; a stdio proxy or a config printer is a second thing to+ keep in step for no client that needs it today. Revisit when a client+ without HTTP transport matters.++## Design Details++### The agent-tool registry (`spree_core`)++Extracted from the assistant branch with a rename, not a rewrite:++```+spree/core/lib/spree/agent_tool.rb # base class: tool_name, description, param, permission, mutating!+spree/core/lib/spree/agent_tools/registry.rb # Spree.agent_tools — registered by class name, resolved on use+spree/core/lib/spree/agent_tools/context.rb # {store, principal, ability, permission_keys}+spree/core/lib/spree/agent_tools/resource_map.rb+spree/core/lib/spree/agent_tools/record_summary.rb+spree/core/app/tools/spree/agent_tools/*.rb # built-in tools+```++A tool is `{name, description, JSON params schema, permission key, mutating+flag, executor}`. Extensions register with `Spree.agent_tools << MyGem::Tools::SyncSupplier`+exactly as they register a delivery-rate provider.++**Context carries a principal, not a user.** The assistant's context holds the+signed-in admin and their ability. Over MCP the principal is a secret key. The+context gains `principal` (an admin user or an API key) and `permission_keys`+resolves from whichever it is: the ability's activated keys for a user, the+key's expanded scopes for an API key. `accessible(relation, action)` still+applies CanCanCan for a user principal; for a key principal the store scope is+the whole tenancy answer, as it is in the Admin API today.++**The resource map is derived, not hand-listed.** Every admin controller+already declares `model_class`, `serializer_class` and `scoped_resource`. Core+owns the map's structure and the refusal for a model whose store scoping is+accidental; `spree_api` fills it in its `to_prepare` by walking+`Spree::Api::V3::Admin::ResourceController` descendants (eager-loaded in every+environment for this purpose), the same way registries are filled after+serializer classes load. The only fact a controller lacks is the dashboard+path used in result links, kept as a small per-resource hash. The existing+spec that compares map entries against controller declarations inverts into a+spec that the derived map contains every controller.++### Tool catalog++| Tier | Tools | Parameters come from | Offered to |+|---|---|---|---|+| Generic reads | `search_resources`, `get_resource`, `describe_resource` | Resource map; each model's Ransack allowlists; admin serializers | any `read_*` scope, filtered per resource |+| Reporting | `query_report`, `explain_report`, `describe_reporting`, `list_saved_reports`, `get_saved_report`, `save_report` | `Spree.reporting` registry (same source as the OpenAPI spec) | `read_reports` + the per-subject scopes the reporting endpoints already check |+| Workflow tools | one per exposed workflow: `orders_cancel`, `orders_complete`, `fulfillments_create`, `fulfillments_fulfill`, `fulfillments_mark_delivered`, `returns_approve`, `returns_refund`, `refunds_create`, `payments_capture`, `products_activate`, `price_lists_activate`, `stock_transfers_receive`, … | the workflow's `perform` signature and its YARD `@param` block | the permission named in the allowlist |+| Generic record writes | `create_resource`, `update_resource`, `delete_resource` | Resource map; the controller's permitted attributes via the generated `admin.yaml` request schemas | matching `write_*` scope, only for resources with no create/update workflow |++`describe_resource` returns, for one resource: filterable fields and named+scopes (reads), the writable attribute schema from the OpenAPI spec where the+resource has no workflow, the workflow tools that take a record of this+resource as their subject, status values from `has_status`, and for+typed-subclass families the `type` shorthands from the family's types+endpoint. The model discovers vocabulary instead of guessing it, and nothing+is enumerated by hand in a tool description.++`search_resources` results are compact by design: a summary line, the prefixed+id, a dashboard link, and only the fields the caller asked for. MCP results+land in the model's context window verbatim, so an admin serializer's full+payload is the wrong default; `get_resource` is the full record.++### Workflow tools++**The allowlist.** One file in core:++```ruby+Spree.agent_tools.expose_workflows(+ order_cancel_workflow: 'write_orders',+ order_complete_workflow: 'write_orders',+ fulfillment_create_workflow: 'write_orders',+ fulfillment_mark_delivered_workflow: 'write_orders',+ return_approve_workflow: 'write_returns',+ refund_create_workflow: 'write_orders',+ product_create_workflow: 'write_products',+ product_activate_workflow: 'write_products',+ # … the workflows the admin controllers call, minus internal ones+)+```++Keys are `Spree::Dependencies` keys, so the tool follows whatever class the+host app has registered. The starting set is the 57 workflows the admin+controllers called on 2026-09-16, minus those a controller reaches only+indirectly or that exist for the platform rather than a merchant (invitation+acceptance, customer anonymisation, payout sweeps). An entry may carry+`except:` to hide a deprecated parameter (`restock_items` on cancel) and+`summary:` to override the generated confirmation line.++**Controllers are the reference wiring.** For every exposed workflow there is+an admin controller action that calls it, and that action defines how a+request becomes keywords: which lookups are store-scoped+(`current_store.order_cancellation_reasons.find_by_prefix_id!`), which+principal is injected (`canceler: try_spree_current_user`), which lock is+taken (`with_order_lock`). The adapter follows those rules generically rather+than per tool, and a contract spec walks the admin controllers, collects every+`Spree.*_workflow` they invoke, and fails when one is neither exposed nor+named in an explicit exclusion list with a reason. The permission in the+allowlist must equal the controller's `scoped_resource` write scope; the same+spec checks it.++**Schema derivation.** `Method#parameters` on `perform` gives each keyword+and whether it is required. The YARD `@param name [Type] description` lines+above `perform` give the type and the description, parsed once at boot from+the workflow's source and cached; 105 of 109 workflows document every+parameter today, and the spec fails on an exposed workflow with an+undocumented one. Type mapping:++- A Spree model (`[Spree::Order]`, `[Spree::Fulfillment]`) becomes a string+ parameter taking a prefixed id, resolved to a record through the resource+ map under the context's store (and the ability, for a user principal). A+ model the map does not know cannot be exposed; a value that does not+ resolve is a tool error naming the parameter.+- `String`, `Boolean`, `Numeric`, `BigDecimal`, `Time` become the matching+ JSON primitives; `Time` is ISO 8601.+- `Hash` and `Array<Hash>` pass through as objects, described by the+ parameter's doc text.+- Principal parameters — `canceler`, `approver`, `reviewer`, `created_by`,+ `refunder` — are removed from the schema and injected from the context as+ `context.actor`: the admin user for a user principal, the API key for a key+ principal. `6.0-action-actors.md` makes the key a valid actor on the order+ operations, so an MCP cancel records the key that did it; on associations+ not yet converted (6.1 in that plan) a key actor is dropped to `nil` by the+ adapter rather than raising, and the tool result says the change was+ unattributed.++**Naming.** The workflow key with dots replaced by underscores+(`orders.cancel` → `orders_cancel`), because MCP tool names allow only+letters, digits, underscore and hyphen. The description is the workflow+class's leading comment, first paragraph.++**Execution.** The adapter takes the same row lock the controller takes for+an order-subject workflow, calls the workflow, and shapes the result: on+success a one-line summary ("Cancel order R123456789", generated from the+workflow key and the subject record's summary line unless the allowlist+overrides it) plus the returned record in its compact form; on failure a tool+error carrying the record's errors or the result's error text, so the model+can self-correct instead of retrying blind.++**Count.** About 50 workflow tools after exclusions. A key sees only the+tools its scopes permit, so a key minted for order operations sees around+twenty. If a client's list limit ever bites, the fallback is grouping a family+behind one tool at the listing layer — the registry does not change.++### Generic record writes++Only for resources whose controller declares no create or update workflow:+markets, channels, delivery methods and profiles, payment methods, tax+categories and rates, roles, customer groups, allowed origins, store+settings. These take exactly the path the API takes for them — permitted+attributes from `admin.yaml`, assign, save with validations — and the+summary is generated ("Update market EU: currencies EUR, PLN"). A resource+with a workflow refuses the generic write and names the workflow tool.+`delete_resource` follows the same rule, since some controllers destroy+through a workflow (`product_destroy_workflow`) and some directly.++### What is not exposed at 6.0++- **The 17 Tier 1 services** the controllers call for order editing, fees,+ discounts, addresses, stock levels and store credits. They arrive as+ workflows, not through a second adapter.+- **Task tools.** Every one the first draft listed is one workflow+ (`update_product_status` → `products_activate` / `products_draft` /+ `products_archive`) or a generic write (`create_export`). The branch's+ `update_product_status` is retired; the import mapping proposal stays in+ the assistant because it needs the model.+- **Files.** Media uploads, import files, label downloads. MCP carries text+ and structured content.+- **Money moves without a person.** Refund and capture are workflow tools+ under `write_orders`, guarded by the key's scope and the client's+ confirmation only. The docs say plainly: an agent that should read orders+ but never refund gets a key without the write scope.++### The MCP gem (`spree/mcp`, gem `spree_mcp`)++```+spree/mcp/+ app/controllers/spree/api/v3/admin/mcp_controller.rb # POST /api/v3/admin/mcp → Server.for(key).handle_json+ lib/spree/mcp/engine.rb # draws the route inside the admin API namespace+ lib/spree/mcp/server.rb # builds an MCP::Server for one principal from the registry+ lib/spree/mcp/tool_adapter.rb # Spree::AgentTool → MCP::Tool definition + handler+ spree_mcp.gemspec # spree_core, spree_api, mcp ~> 1.5+```++- **Endpoint:** `POST /api/v3/admin/mcp`, one JSON-RPC message per request,+ JSON response. Stateless: no session id, any Puma worker answers any+ request. The optional `GET` server-to-client stream is not offered at 6.0.+- **Authentication:** the controller inherits the admin API's+ `authenticate_secret_key!` and store context, so the key selects the store+ and `X-Spree-Store` is honoured only when it matches the key's store, as+ today. JWT is refused: this is a machine surface. Rate limiting and+ security headers come with the base controller.+- **Per-request server:** `Spree::Mcp::Server.for(principal)` builds an+ `MCP::Server` whose tool list is the registry filtered by the key's+ expanded scopes and whose `server_context` is the+ `Spree::AgentTools::Context` for that key. Building it is cheap (tool+ definitions are memoised per registry state); nothing is cached across+ principals.+- **Tool listing:** `tools/list` returns the registry filtered by the key's+ expanded scopes (`read_all` / `write_all` expand as they do for the API).+ Listing is stable for a given key, so the 2026-07-28 cache hints apply.+ Tool annotations carry `readOnlyHint` for reads and `destructiveHint` for+ mutating tools, from the registry's `mutating` flag, so clients that gate+ confirmation on annotations do the right thing.+- **Tool calls:** the adapter validates arguments against the tool's schema,+ builds the context from the key, runs the executor, and returns the result+ as structured content plus a text summary. A refusal from the executor+ (`{error: …}`) is a tool error, not a protocol error, so the model can+ self-correct — same rule as the CLI's 403 remediation text.+- **Resources and prompts:** none at 6.0. `describe_resource` is a tool+ because clients handle tools uniformly and resources unevenly.++### Permissions, end to end++1. **Minting decides what exists.** An admin with `write_api_keys` mints a+ secret key and picks scopes, as for any integration. `tools/list` for that+ key contains only what those scopes permit; a tool the key cannot use is+ never named to the model.+2. **The key decides the store.** Tenancy comes from the key, never from a+ parameter; every lookup runs through the store-scoped resource map, so+ another store's prefixed id is "not found".+3. **Every call re-checks the scope**, so revoking or narrowing a key takes+ effect on the next call. Revocation stays the kill switch.+4. **The workflow decides whether the change is allowed** and refuses in its+ own words, which the tool error carries back.+5. **The client asks the human.** Claude Code prompts before each MCP tool+ call unless the user allowed that tool in settings; reads can be allowed+ once and writes left prompting. Mutating tools carry `destructiveHint`+ for clients that gate on annotations.++Attribution: with `6.0-action-actors.md`, a workflow run over MCP records+the API key as `canceler` / `approver` / `created_by`, so the order timeline+reads "cancelled by WMS connector" rather than nothing. A key principal gets+no record-level CanCanCan filtering, matching the Admin API's treatment of+key requests today. Department- or seller-limited agents+are the assistant's job with its signed-in user, or a later per-key ability.+Not in scope, but cheap and worth a follow-up: an audit event per mutating+tool call naming the key, which the Admin API also lacks for key requests.++### How a client decides to use it++No command. The server's tools join the model's tool list with their names+and descriptions and the model picks from the prompt. Three things make that+reliable:++- **Descriptions and the server's `instructions` field.** MCP lets a server+ send short usage guidance at discovery; ours says search first,+ `describe_resource` for vocabulary, then act.+- **Scope-filtered lists.** A merchant key sees around twenty tools, not the+ catalog. Claude Code additionally defers large MCP tool lists and loads+ tools on demand.+- **The `spree-cli` skill draws the line** for developer agents that have+ both a shell and the server: bulk, scripting and debugging go through+ `spree api`; conversational operations go through MCP.++### Auth flow and where the key lives++1. **Mint.** An admin with `write_api_keys` creates a secret key in the+ dashboard: a name that says which agent holds it ("Claude Code, orders"),+ and the scopes. The plaintext is shown once; only the digest is stored.+2. **Place.** The client configuration carries the key as a request header+ on every call (see the per-client table). Nothing is exchanged or+ refreshed.+3. **Authenticate.** Each request runs the Admin API's digest lookup. The+ key selects the store and the scopes. A missing, unknown or revoked key+ answers 401 with a JSON-RPC error whose text names the header to set and+ where to mint a key, because that text is what the model and the person+ read.+4. **Rotate or revoke** in the dashboard; the next request fails and the+ client surfaces the error.++| Client | Where the key goes |+|---|---|+| Claude Code | `claude mcp add --transport http spree-admin https://<shop>/api/v3/admin/mcp --header "X-Spree-API-Key: sk_…"` (user config); or a committed project `.mcp.json` referencing `${SPREE_API_KEY}` so each developer exports their own key and none lands in git |+| Cursor | `.cursor/mcp.json`: `url` plus a `headers` map |+| VS Code | `.vscode/mcp.json`: `type: http`, `url`, `headers`, with a prompted secret input so the value is not stored in the file |+| Claude Desktop | The connector UI accepts a URL and expects OAuth or no auth; until the OAuth lane ships, a stdio bridge that forwards the header |+| claude.ai | Not a supported client until the OAuth lane ships |+| In-house agents | Whatever HTTP client they use, with either header form |++The docs page (Migration Path step 5) carries these snippets; the CLI+config printer that would have generated them was deferred (Key Decisions).++### How this differs from the Admin API CLI++Both surfaces exist because they serve different callers, not because one is+the old way. The `spree api` command group stays the primary tool for+developer agents.++| | `spree api` (CLI) | MCP server |+|---|---|---|+| **Caller** | Agents with a shell: Claude Code, Cursor, CI scripts, humans | Clients that cannot shell out: Claude Desktop and claude.ai connectors, ChatGPT, Cursor's MCP panel, in-house agents; merchants who never open a terminal |+| **Vocabulary** | Generic HTTP verbs plus `endpoints` / `schema` from the OpenAPI spec; the agent composes calls | Curated tools with job-level semantics and generated schemas; the model picks a tool |+| **Where results go** | Stdout; the agent decides what to read, can pipe to `jq` | Straight into the model's context; results must be compact and summarised |+| **Writes** | Anything the key's scopes allow, raw payloads | One scope-gated tool per workflow with a derived schema; every write returns a human summary for the client's confirmation prompt |+| **Setup** | Zero-config inside a project (auto-minted read key) | A minted key in the client's MCP config; `spree mcp` (later) can print that config |+| **Credentials** | Layered: flags, env, project auto-mint, profiles | Secret key header now; OAuth 2.1 later |+| **Coverage** | Every endpoint, by construction | The registry's tools; a gap is filled by a map entry or a task tool, not by a new endpoint |+| **Substrate** | HTTP to the Admin API | In-process calls to the same workflows the controllers use |+| **Best at** | Bulk, scripting, debugging, anything the schema tools can express | Conversational merchandising, reporting questions, guided setup |++The rule of thumb for a developer agent: if it has a shell, `spree api`. The+rule for the MCP catalog: if a write is not a workflow, it is not a tool yet.++### The assistant, later++`6.0-dashboard-assistant.md` rebases onto `Spree.agent_tools`: its+`Spree::Assistant::Tool` and registry are deleted, its RubyLLM adapter reads+the core registry, its context becomes a user-principal `Spree::AgentTools::Context`,+and its approval gate keys off the same `mutating` flag. Chat persistence,+streaming, provider integrations and the panel are untouched. What the+assistant keeps that MCP does not have: server-side approval, record-level+CanCanCan filtering for a signed-in admin, and result cards rendered from the+same structured content.++### Testing++No LLM anywhere in the suites: an MCP client is a JSON-RPC sender, so every+layer is exercised with factories, real workflows and JSON strings. Four+layers, each in the engine that owns the code, all run through+`pnpm test:rspec <engine>`.++**Core — registry and adapter units (`spree_core`).** The tool DSL, registry,+record summary and context specs move from the assistant branch. New:++- Context with a key principal: `permission_keys` equals the key's expanded+ scopes (`read_all` expands), `accessible` applies no ability filter for a+ key and the existing record-level filter for a user.+- Schema derivation against a workflow defined inline in the spec (required+ and optional keywords, a YARD block, a principal parameter, a deprecated+ one): required list, JSON types, description text, principal removed,+ `except:` honoured, a model-typed parameter rendered as a prefixed-id+ string, an undocumented parameter failing loudly.+- Argument resolution: a prefixed id resolves within the context's store;+ another store's id and an unknown id return a tool error naming the+ parameter; a value of the wrong JSON type is refused before the workflow+ runs.+- Execution through real workflows with factories: `orders_cancel` on a+ completed order cancels it and returns the summary line and compact+ record; on an order whose goods have shipped it returns the workflow's own+ refusal text as a tool error; the order-subject lock is taken (`with_lock`+ observed on the record). One such spec per workflow *family* (order,+ fulfillment, return, product, price list), not per workflow — the+ workflows have their own suites and the adapter is generic.+- Generic record writes: an update on a market persists through validations;+ the same call on a product (which has a workflow) is refused and names+ `products_update`.++**API — contract specs (`spree_api`, where the controllers are).**++- Resource map derivation: every admin controller with a `scoped_resource`+ appears in the map with its model, serializer and permission; a controller+ whose model has accidental store scoping is refused at boot.+- Allowlist contract: every `Spree::Workflow` subclass an admin controller+ invokes (collected by scanning the admin controller sources for+ `Spree.<key>` and resolving through `Spree::Dependencies`) is exposed or+ named in the exclusion list with a reason; every allowlist permission+ equals the invoking controller's `scoped_resource` write scope; every+ exposed workflow's model-typed parameters are resources the map knows.+- A golden catalog: `tools/list` for a `read_all` + `write_all` key,+ serialised deterministically and committed under `spec/fixtures`. Any+ change to a workflow signature, a YARD line or the allowlist shows up as a+ diff in review, the way `admin.yaml` does for the REST surface. Regenerated+ with a rake task, never hand-edited.++**MCP — protocol and endpoint (`spree_mcp`, own dummy app like+`spree_opentelemetry`).**++- Adapter round-trip: a `Spree::AgentTool` becomes an `MCP::Tool` with a+ valid name, the derived input schema, and `readOnlyHint` /+ `destructiveHint` set from the mutating flag.+- Server units with `handle_json`, no HTTP: `server/discover` answers the+ 2026-07-28 revision; `tools/list` for a key with `read_products` returns+ exactly the read tools for product-scoped resources and nothing mutating;+ `tools/call` on a read tool returns structured content; `tools/call` on a+ tool the key lacks the scope for is "tool not found", not "forbidden" (the+ tool was never offered); malformed arguments are a JSON-RPC invalid-params+ error with the parameter named.+- Request specs against `POST /api/v3/admin/mcp` with+ `create(:api_key, :secret, store:, scopes:)` and the plaintext token in+ `X-Spree-API-Key`, as `api_keys_controller_spec` does: no key → 401; a+ JWT → 401; a key whose store differs from `X-Spree-Store` → 404; a+ well-formed `tools/call` on `fulfillments_mark_delivered` marks the+ fulfillment delivered end to end through the real workflow. Request+ specs, not controller specs: the endpoint is JSON-RPC, so the unit under+ test is the whole request, and `render_views` does not apply.++**What is deliberately not tested here.**++- The workflows' behaviour — their own suites own it; the adapter specs+ assert only that the call reached the workflow with the right keywords+ and that its result was shaped correctly.+- OpenAPI: the endpoint is JSON-RPC, excluded from `swaggerize`, documented+ on the docs page and by the golden catalog instead.+- A live MCP client. The gem's own conformance is its maintainers' job; the+ QA environment from `/project:implement-plan` is where Claude Code is+ pointed at the endpoint by hand before the PR is opened.++`scripts/test/` gains `mcp` in its engine list in the same PR that adds the+gem, so `pnpm test:changed` picks its specs up.++## Migration Path++0. **`6.0-action-actors.md` lands first** (schema change; the context's+ `actor` and the injection rule below rely on it).+1. **Registry into core** (`spree_core`): move the tool base class, registry,+ context, resource map and record summary from the assistant branch, renamed+ as above, with the principal abstraction. Derive the resource map from the+ controllers. Bring the branch's specs across. See "Taking the code from the+ assistant branch" below for exactly what moves and in what order.+2. **Reporting tools** over `Spree.reporting`, reusing the reporting+ controller's member-level authorization for API keys.+3. **Workflow tools**: the allowlist in core, the adapter (schema+ derivation, argument resolution, principal injection, locks, result+ shaping), the contract spec against the admin controllers, and the+ generic record writes for resources without a workflow.+ `describe_resource` gains the writable schema and the workflow tools per+ resource.+4. **`spree_mcp` gem**: engine and route, the controller over `handle_json`,+ the adapter, the per-principal server; the protocol and request specs+ above, plus `mcp` in `scripts/test/`.+5. **Docs and skill**: a `docs/developer/agentic/admin-mcp.mdx` page next to+ the docs-MCP page (setup per client, minting a key with the right scopes,+ what the tools are), and a cross-reference in the `spree-cli` agent skill+ saying when to reach for which.+6. **Later, outside this plan:** `spree mcp` stdio wrapper in `@spree/cli`+ that proxies to the mounted endpoint and prints client configs; OAuth 2.1+ for hosted consumer connectors; a shopper-facing Storefront MCP (own plan).++### Taking the code from the assistant branch++The registry is lifted from `feat/dash-assistant` (unmerged) into a branch+cut from `main`, and the assistant branch is then rebased to consume it. The+lift happens first so the registry never exists in two places; merging the+assistant first and extracting afterwards would carry RubyLLM into the+history of a core contract and leave two copies to reconcile.++**What moves, measured on the branch (2026-09-15):**++| From `spree/assistant/…` | Lines | To `spree/core/…` |+|---|---|---|+| `lib/spree/assistant/tool.rb` | | `lib/spree/agent_tool.rb` — `Spree::AgentTool` |+| `lib/spree/assistant/registry.rb` | | `lib/spree/agent_tools/registry.rb` — exposed as `Spree.agent_tools` |+| `lib/spree/assistant/context.rb` | | `lib/spree/agent_tools/context.rb` — gains the principal |+| `lib/spree/assistant/resource_map.rb` | | `lib/spree/agent_tools/resource_map.rb` — derived from controllers |+| `lib/spree/assistant/record_summary.rb` | | `lib/spree/agent_tools/record_summary.rb` |+| *registry subtotal* | 686 | |+| `app/tools/spree/assistant/tools/*.rb` (8 tools; `update_product_status` is retired, see below) | 704 | `app/tools/spree/agent_tools/*.rb` |+| `spec/lib/spree/assistant/{resource_map,record_summary}_spec.rb`, `spec/tools/**`, `spec/authorization_spec.rb` | 546 | `spec/lib/spree/agent_tools/**`, `spec/tools/**` |++About 1,900 lines of Ruby including specs move; nothing is rewritten. The+eight tools reference only the registry classes plus `Spree::Export`,+`Spree::ImportMapping` and `Spree::Products::Update`, all already in core.++**What stays on the assistant branch:** the RubyLLM adapter, the turn loop,+chat and message models, providers and integrations, controllers,+serializers and their specs (about 2,300 lines), and the dashboard panel+(about 1,800 lines of TypeScript). The assistant plan's phases are+unaffected beyond the rebase.++**Four changes made during the move, not after:**++1. **Rename.** `Spree::Assistant::Tool` → `Spree::AgentTool`,+ `Spree::Assistant::Tools::X` → `Spree::AgentTools::X`,+ `Spree::Assistant.tools` → `Spree.agent_tools`. Tool *names* on the wire+ (`search_resources`, `update_product_status`, …) do not change: the+ assistant's persisted tool-call rows reference them.+2. **Principal on the context.** `Context.new(store:, user:)` keeps working+ for the assistant; `Context.new(store:, api_key:)` is added for MCP.+ `permission_keys` resolves from the ability for a user and from+ `Spree.permissions.expand_keys(api_key.scopes)` for a key; `accessible`+ applies CanCanCan only for a user principal.+3. **Derived resource map.** The hand-written `ENTRIES` list is replaced by+ a walk over `Spree::Api::V3::Admin::ResourceController` descendants,+ reading `model_class`, `serializer_class` and `_scoped_resource`. The+ dashboard paths become a per-resource hash the assistant contributes.+ The branch's "every entry matches its controller" spec inverts into "every+ controller with a scoped resource is in the map". The scoping refusal+ (`UnscopedResourceError`) is kept as is.+4. **`update_product_status` is retired.** The products workflows+ (`activate`, `draft`, `archive`) become tools by the allowlist, so the+ hand-written tool would be a duplicate. Its spec's assertions on the+ summary line and the record-level authorisation check move to the workflow+ adapter's spec. `create_export` folds into `create_resource` on exports.++**Order of operations:**++1. Cut `feat/agent-tools` from `main`. Copy the files above with+ `git checkout feat/dash-assistant -- <path>` and `git mv` them into place,+ so blame follows the code; apply the three changes; run the moved specs+ under `pnpm test:rspec core`.+2. Open the PR for step 1 alone. It is reviewable in isolation and has no+ MCP or LLM code in it.+3. After it merges, rebase `feat/dash-assistant` onto `main`, delete the+ moved files from `spree/assistant`, point the RubyLLM adapter and+ `RunTurn` at `Spree.agent_tools` and the core context, and run the+ assistant suite. The branch shrinks by the lines core gained.+4. `spree_mcp` (step 4 of the Migration Path) starts from `main` once step+ 1 is in; it never branches from the assistant.++## Constraints on Current Work++- **Do not add tool classes under `Spree::Assistant::Tools`** on the+ assistant branch or anywhere else; new tools go under `Spree::AgentTools`+ once step 1 lands, and until then are held.+- **New admin controllers must declare `model_class`, `serializer_class` and+ `scoped_resource`** (already the rule) — the derived resource map reads+ them, so an omission now hides a resource from every agent surface.+- **A new back-office write is a workflow registered in `Spree::Dependencies`+ and added to the allowlist in the same PR.** A Tier 1 service called from+ an admin controller is invisible to agents until it is promoted; do not+ add new ones for write paths.+- **A controller with a workflow must declare it through `create_workflow` /+ `update_workflow`**, never a hand-written action; the generic record writes+ refuse a resource with a workflow, and the contract spec reads the+ declaration.+- **Every `perform` parameter carries a YARD `@param` with a type**, and a+ record parameter is typed as a model the resource map knows. Principal+ parameters use the established names (`canceler`, `approver`, `reviewer`,+ `created_by`) so the adapter injects them; a new name for the same idea+ would be offered to the caller as a free parameter.+- **Keep `admin.yaml` regenerated after Admin API changes**; the writable+ schemas `describe_resource` returns come from it.+- **Keep tool results compact.** A tool that returns a full admin payload by+ default is a defect: results land in the model's context.++## Open Questions++Nothing blocks implementation. Two items are deliberately deferred:++- **OAuth 2.1 for hosted consumer connectors** (claude.ai connectors,+ ChatGPT). Unblocked by Spree gaining an authorization-server capability, or+ by a decision to delegate to an external one; `6.0-platform-auth` phase 7+ (OIDC login) does not provide it. The 2026-07-28 revision replaced dynamic+ client registration with client ID metadata documents, so that design+ should start from the current spec, not the 2025 one.+- **A `spree mcp` CLI command** (config printer or stdio proxy). Unblocked by+ a client that cannot reach a Streamable HTTP endpoint, or by setup friction+ reported from the docs page in step 6.++## References++- `docs/plans/5.5-admin-api-cli.md` — CLI-first sequencing and the future-lanes table this plan executes+- `docs/plans/6.0-dashboard-assistant.md` — the registry's origin; superseded on "No MCP in 6.0"+- `docs/plans/6.0-analytics-semantic-layer.md` step 10 — the reporting tool shape+- `docs/plans/6.0-admin-rbac.md`, `docs/plans/5.5-admin-api-key-scopes.md` — permission catalog and scopes+- `docs/developer/agentic/mcp.mdx` — the documentation MCP server, a sibling page+- Official Ruby SDK: https://github.com/modelcontextprotocol/ruby-sdk (1.5.1; 2026-07-28 revision since 1.2.0)+- MCP 2026-07-28 specification changelog: https://modelcontextprotocol.io/specification/2026-07-28/changelogdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 19820bde69..1097fb7e91 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -5553,3 +5553,91 @@ backed by an index) and that key on its Ransack allowlist, or it cannot bedeclared in a config file. Credential attributes on payment methods andintegrations must never read back in plain text through the Admin API;`introspect` relies on that. Do not add a Ruby-side YAML loader to core.+++## 2026-09-15 — Admin MCP ships in 6.0 over a core agent-tool registry; the assistant follows it++Plan: `6.0-mcp-server.md`. Supersedes the "No MCP in 6.0" decision in+`6.0-dashboard-assistant.md` (2026-08-20) and executes the future-lanes table+in `5.5-admin-api-cli.md`, whose CLI-first precondition is met now that+`spree api` has shipped.++**Decision.** The tool registry the assistant branch built+(`{name, description, params schema, permission key, mutating flag,+executor}`) moves into `spree_core` as `Spree::AgentTool` /+`Spree.agent_tools`, beside `Spree.integrations` and `Spree.reporting`, so an+extension registers a tool without depending on any adapter gem. A new+optional gem `spree_mcp` mounts the official `mcp` Ruby gem's Streamable HTTP+transport at `/api/v3/admin/mcp`, authenticates with secret keys and offers+only the tools the key's scopes permit. The assistant rebases onto the same+registry afterwards. No new `spree_ai` or `spree_agents` gem.++**Catalog shape.** Never one tool per endpoint. Generic reads and generic+writes over a resource map derived from the admin controllers, with writable+schemas read from the generated `admin.yaml`; reporting tools over+`Spree.reporting`; a short list of task tools only where a job crosses+records. Writes are scope-gated and confirmed by the MCP client; the+server-side approval gate stays an assistant feature.++**Consequences for other work.** New admin controllers must declare+`model_class`, `serializer_class` and `scoped_resource`, and expose their+workflow through `create_workflow` / `update_workflow`, or the generic tools+cannot see them. Tool results must stay compact because they land in the+model's context. No new tools under `Spree::Assistant::Tools`.+++## 2026-09-16 — Workflows are the agent write tools; exposure is an allowlist in core++Plan: `6.0-mcp-server.md`. Refines the 2026-09-15 entry above.++Reviewing the orders and products controllers showed that the Admin API has+no direct record writes left on its write paths: the base controller calls+the declared `create_workflow` / `update_workflow`, every member action calls+a registered workflow, and a workflow's `perform` keyword signature with its+YARD `@param` block is a machine-readable contract.++**Decision.** Each exposed workflow is one agent tool with a schema derived+from `perform`; no hand-written task tools. Exposure is+`Spree.agent_tools.expose_workflows(<dependency key> => <permission>)` in+`spree_core`, keyed by `Spree::Dependencies` key so a host app's replacement+workflow keeps the tool. Generic `create_resource` / `update_resource` /+`delete_resource` exist only for resources whose controller declares no+workflow and refuse the rest. Tier 1 services still called from controllers+are not adapted; they are promoted to workflows over time.++**Consequences for other work.** A new back-office write is a workflow plus+an allowlist entry in the same PR. `perform` parameters need typed YARD+docs; record parameters must be models the resource map knows; principal+parameters keep the established names so they are injected, never accepted+from a caller. A contract spec fails when an admin controller invokes a+workflow that is neither exposed nor explicitly excluded.+++## 2026-09-16 — The API key is an actor; "who did this" associations become polymorphic++Plan: `6.0-action-actors.md`, shipping before `6.0-mcp-server.md`.++Every association that records who performed an action (`canceler`,+`approver`, `created_by`, `refunder`, `received_by`, …) pointed at the admin+user class only, so a write made with a secret API key — a warehouse+connector, an integration, soon any MCP client — recorded nobody.++**Decision.** Those associations are declared with `acted_by`, which makes+them polymorphic over `Spree.actor_classes` (the admin user class and+`Spree::ApiKey`; extensions register more). The Admin API passes+`current_actor` — the signed-in admin or the authenticating key — to+workflows in place of the user. 6.0 converts the order operations (orders,+refunds, returns, exchanges, claims, stock receipts: 8 columns on 6 tables);+the remaining 13 convert in 6.1. Serializers expose `<name>_type` beside+`<name>_id`. A transitional reader resolves un-backfilled rows through the+admin user class with a deprecation warning until 6.1. Rejected: user-bound+personal keys (platforms are retiring them; a connector is not a person) and+waiting for OAuth (leaves 6.0 key writes unattributed). OAuth, when it comes,+resolves a token to one of these two actor kinds.++**Consequences for other work.** New "who did this" associations use+`acted_by`, never `belongs_to … class_name: Spree.admin_user_class`;+ownership associations that gate visibility (`Import#user`, `Export#user`,+`SavedReport#user`) keep the plain form. Controllers pass `current_actor`,+not `try_spree_current_user`, for actor keywords. Workflow principal+parameters stay `[Object, nil]` and are assigned, not inspected.