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
Changed order creation and stock upserts into workflows
Damian Legawiecfd3204cf36e2
diff --git a/docs/plans/6.0-mcp-server.md b/docs/plans/6.0-mcp-server.mdindex 690da4402d..dba18f1191 100644--- a/docs/plans/6.0-mcp-server.md+++ b/docs/plans/6.0-mcp-server.md@@ -1,10 +1,10 @@# Admin MCP Server-**Status:** In Review — Migration Path steps 1–5 (core registry, reporting tools, workflow tools and generic record writes, the `spree_mcp` gem, docs) built on `feat/spree-mcp-server`, PR spree/spree#14664+**Status:** In Review — Migration Path steps 1–5 built on `feat/spree-mcp-server`, PR spree/spree#14664. **Step 6 (execution through the Admin API) is the direction the branch is moving to before merge**, decided 2026-10-10: the in-process execution path the first five steps built is being replaced, the tool catalog is not.**Target:** Spree 6.0**Depends on:** `6.0-action-actors.md` (shipped 2026-09-16 — the API key is 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+**Last updated:** 2026-10-10**Tracking:** Linear V-3645 · GitHub spree/spree#14656## Summary@@ -18,10 +18,12 @@ adapter over a Spree-owned **agent-tool registry** that lives in `spree_core`;the dashboard chat assistant (`6.0-dashboard-assistant.md`, unmerged) becomesthe second adapter over that same registry once this ships. The order isdeliberate: 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.+Admin API: generic read and write tools mapped to the list, show, create,+update and destroy operations, reporting tools mapped to the reporting+endpoints, and one tool per non-CRUD member action (cancel, complete, capture,+fulfil, approve, activate). Every schema comes from the operation's OpenAPI+request shape, and every call is dispatched through the Admin API in-process,+so a tool reaches data exactly the way any other client does.## Key Decisions (do not deviate without discussion)@@ -49,16 +51,18 @@ because every back-office write already is a workflow.at forty). The catalog is four tiers — generic reads, reporting, workflowtools, generic record writes — and its *parameters* come from registriesSpree 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+- **Operations are the write tools (2026-10-10; replaces "Workflows are the+ write tools", 2026-09-16).** A tool names an Admin API operation, and the+ controller behind it runs whatever workflow it declares. The earlier+ decision reached for the workflow directly because its `perform` signature+ and YARD block were the only machine-readable contract available; the+ operation's OpenAPI request schema is a better one, and it is the contract+ clients already use. What the catalog keys on therefore changes too — see+ "the catalog is keyed by operation" below.++ The earlier reasoning still holds for *why* writes are safe: the base+ controller calls the declared `create_workflow` / `update_workflow` rather+ than saving records, so dispatching to it runs the same gate. Rejected: a single `run_workflow` tool (every write becomes two orthree calls and the client can only confirm "run_workflow", not the action)and a hybrid of first-class families plus a generic tail (two conventionsthat drift).@@ -74,11 +78,17 @@ because every back-office write already is a workflow.on each workflow class (scatters the catalog across 57 files) and agenerated manifest from controller source (a second `admin.yaml` toregenerate).-- **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+- **~~Workflows only; Tier 1 services are promoted, not adapted~~+ (2026-09-16; withdrawn 2026-10-10).** This gated exposure on a service+ becoming a workflow, because the adapter needed a `perform` signature to+ derive a schema from. Dispatch needs no signature: an endpoint backed by a+ service is as reachable as one backed by a workflow. So order editing,+ fees, discounts and stock become exposable as soon as their endpoints+ exist. Services are still promoted to workflows for their own sake — hooks,+ one gate per write — but that work no longer blocks agents. The original+ text read: seventeen services the admin controllers still call are not+ exposed; order editing reaches agents as those paths become workflows,+ never through a secondadapter 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@@ -103,12 +113,92 @@ because every back-office write already is a workflow.confirmation prompt (Claude Code and Claude Desktop ask before running atool) has something to show. The assistant's server-side approval gateremains an assistant concern, built on the same `mutating` flag.+- **Tools execute through the Admin API, not beside it (2026-10-10).**+ Superseding the execution half of the decisions below. The first five steps+ built the tools as a second way into the same data: their own store scoping,+ their own permission checks, their own Ransack call, their own writable+ attribute lists, their own error shape. Three faults found by probing the+ branch show the cost, and all three are the same fault:++ - **A prefixed id filters nothing.** `search_resources` calls `.ransack`+ directly, skipping the `ResourceController` step that decodes prefixed+ ids. Filtering variants by `product_id_eq: "prod_3uWpPTcf5W"` — the only+ form the tools ever *return* — answers `total=0`, where the raw id+ answers 3. No error: a model reports the empty result as fact.+ - **Extension attributes are invisible.** The writable list is derived from+ each controller's `resource_permitted_attributes` but not from the+ model's `additional_permitted_attributes`, so an extension adding+ `brand_id` can be written through the API and not through an agent.+ - **A workflow trusted ids its one caller had already scoped.** The stock+ upsert wrote to whichever shelf an id named, including another store's,+ because the check lived in the controller. Fixed by moving the scoping+ into the workflow — which is the same lesson at a smaller scale.++ Every guard added to the Admin API should protect agents by construction,+ not after someone remembers to copy it. So a tool call runs the real request+ path: routing, authentication, the controller, the serializer, the error+ format.++- **In-process dispatch, never HTTP to itself (2026-10-10).** The Ruby adapter+ builds a Rack env and calls `Rails.application.call`, forwarding the+ caller's own credential and `Host` header — no internal "trusted" header+ that skips authentication, which would rebuild the second boundary this+ decision exists to remove. A socket back to the same app holds one Puma+ thread waiting on another, so a handful of concurrent tool calls on a small+ pool deadlocks the app; dispatch has the same behaviour without that, and+ without TLS, DNS or timeouts.++ **`Spree::Current` does not reset across a nested dispatch**, because the+ executor is re-entrant. Probed on this branch: an inner `call` left the+ outer request's store intact but **overwrote its currency** (`GBP` → `USD`).+ The adapter snapshots and restores `Spree::Current` around every dispatch,+ and a spec proves a tool call cannot see or corrupt the MCP request's own+ state. Tool calls do not run inside a transaction opened by the MCP+ controller — each commits or rolls back on its own, like any API request.++- **The catalog is the asset; the executor is replaceable (2026-10-10).** Each+ entry names its operation, its permission, its description and a parameter+ projection. Parameter schemas come from OpenAPI — request bodies,+ `x-spree-filters`, the typed preference unions — rather than from Ruby+ signatures, which is why order creation needed a hand-written tool at all+ (its workflow takes an opaque `params` hash). At 7 the same catalog runs+ under TypeScript with `@spree/admin-sdk`, differing only in which `fetch`+ it is given: global `fetch` for a remote store, the app's own `fetch`+ in-process. The Ruby adapter is a shim with a known end date.++- **The catalog is keyed by operation, not by dependency key (2026-10-10).**+ The step 1–5 allowlist keyed on `Spree::Dependencies`, a mechanism with an+ end date (it is being replaced by workflow hooks), and its contract spec+ scanned controller source for `Spree.<key>` calls. Keying on the OpenAPI+ operation instead lets the contract spec walk `admin.yaml`: every admin+ operation is either in the catalog or on the exclusion list with a reason.+ That is sturdier than reading Ruby source, and it is the same list a+ TypeScript executor reads at 7.++- **One agent turn is one unit of work for rate limiting (2026-10-10).** The+ limiter must not see both the MCP request and each call it dispatches, or a+ single turn counts twice and an agent is throttled at half the rate its+ credential allows. Count the dispatched operations — those are the real+ work — and exempt the MCP envelope.++- **Compact results are the adapter's job until the API has sparse fields+ (2026-10-10).** Index operations return the full admin payload, which is+ more than a model needs and more than its context should hold. If the Admin+ API gains sparse fieldsets the adapter passes the requested fields through;+ until then it trims the response itself. Written down because it decides+ whether "compact by design" is free or is work.++- **A missing endpoint is added to the Admin API first (2026-10-10).** The+ rule the dashboard already follows. The stock upsert and product curation+ this branch reached directly become endpoints, and the tools point at them.+- **Tools execute through workflows, never by writing models (2026-09-15).**A workflow tool calls the registered workflow; a generic record write existsonly for a resource whose controller declares no workflow and takes theexact path the controller takes for it. Validations, hooks, events andwebhooks fire exactly as from the dashboard or the API. The MCP server never- calls its own HTTP endpoints.+ opens a connection to itself; it dispatches to its own endpoints+ in-process.- **Official `mcp` Ruby gem, served by a Spree controller, not by the gem'sRack transport (2026-09-15; transport detail corrected 2026-09-16).** Thegem is maintained by the protocol's working group and has supported the@@ -125,13 +215,21 @@ because every back-office write already is a workflow.`opentelemetry` and `dashboard`, the precedent for optional top-levelengines. `spree_api` does not take the `mcp` dependency; installs that donot 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+- **Generic writes work for every resource (2026-10-10; replaces the+ 2026-09-16 narrowing).** `create_resource` / `update_resource` /+ `delete_resource` dispatch to the create, update and destroy operations,+ so the controller runs whatever workflow it declares. The refusal rule+ below existed only because the generic writes skipped workflows and would+ have been a second way to write the same record; dispatch makes them the+ same way. What is left for a dedicated tool is the non-CRUD member actions+ — cancel, complete, capture, fulfil, approve, activate — which is exactly+ the set of member-action endpoints. Fewer tools, one rule.++ The withdrawn text read: generic writes cover store, market, channel,+ delivery, payment and tax setup — resources whose controllers save the+ record directly — and 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 eachthing. No task tools at 6.0; a composed tool is added only when usage showsa job spanning several workflows that the model fails to sequence.- **Steps 1–5 ship as one pull request (2026-09-16).** The "Order of@@ -199,9 +297,10 @@ spec that the derived map contains every controller.| 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 |+| Generic reads | `search_resources`, `get_resource`, `describe_resource` | The list and show operations; `x-spree-filters` for what can be filtered; 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 writes | `create_resource`, `update_resource`, `delete_resource` | The create, update and destroy operations' OpenAPI request schemas | the operation's own `write_*` scope |+| Action tools | one per non-CRUD member action: `orders_cancel`, `orders_complete`, `fulfillments_fulfill`, `returns_approve`, `refunds_create`, `payments_capture`, `products_activate`, … | the member operation's OpenAPI request schema | the operation's own scope || 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@@ -219,6 +318,16 @@ payload is the wrong default; `get_resource` is the full record.### Workflow tools+> **Superseded by step 6 (2026-10-10).** This section describes how the first+> five steps derived a tool from a workflow's Ruby signature: YARD schema+> derivation, the row lock the adapter took, principal injection from the+> context, `CONTEXT_PARAMETERS`, `UNCONVERTED_PRINCIPAL_PARAMETERS`. Under+> dispatch the controller takes the lock, injects the actor from the+> credential and fills in the store, so all of that machinery is deleted. It+> is kept here as the record of what step 6 removes and why — not as+> instructions. The catalog's shape is in "the catalog is keyed by operation"+> under Key Decisions.+**The allowlist.** One file in core:```ruby@@ -300,15 +409,23 @@ behind one tool at the listing layer — the registry does not change.### Generic record writes+> **Superseded by step 6 (2026-10-10).** The refusal rule below — a resource+> with a workflow refuses the generic write — existed because these writes+> assigned attributes and saved. Dispatched, `update_resource` is a PATCH and+> the controller runs its own workflow, so generic create, update and destroy+> are correct for every resource and the refusal goes.++Only for resources whose controller declares no create or update workflow:markets, channels, delivery methods and profiles, payment methods, taxcategories 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.+settings. Dispatched, these take exactly the path the API takes — the+controller's own `permitted_params`, its own workflow where it declares one+— and the summary is generated ("Update market EU: currencies EUR, PLN").+The refusal rule the step 1–5 build needed is gone: every resource is+writable through these three, because every one reaches its controller.+`delete_resource` is the same, whether the controller destroys through a+workflow or directly.### What is not exposed at 6.0@@ -451,8 +568,8 @@ developer agents.| **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 |+| **Coverage** | Every endpoint, by construction | The catalog's tools, each naming an operation; a capability with no endpoint is an endpoint to add first |+| **Substrate** | HTTP to the Admin API | The same Admin API operations, dispatched in-process || **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@@ -579,9 +696,43 @@ gem, so `pnpm test:changed` picks its specs up.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 skillsaying 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).+6. **Execution through the Admin API** (decided 2026-10-10, before merge).+ Steps 1–5 built the catalog and proved the protocol; this replaces how a+ tool call reaches the data. In order, each part shippable on its own:++ 1. **The dispatcher.** `Spree::AgentTools::ApiDispatch` builds a Rack env+ for a method, path, query and body, forwards the caller's credential+ and `Host`, snapshots and restores `Spree::Current` around the call,+ and returns the parsed status, body and headers. Its specs are the+ contract: a nested call cannot see or corrupt the outer request's+ store, currency or locale, and a failing call returns the API's own+ error body rather than an exception.+ 2. **The catalog becomes data.** Each entry names its operation (method+ and path template), its permission, its description, and which+ parameters it projects. The resource map keeps deriving the resource →+ controller mapping it already derives; what changes is that a tool+ holds a route rather than a model and a Ransack call.+ 3. **Reads move first.** `search_resources`, `get_resource` and+ `describe_resource` dispatch to `index`/`show`. This alone fixes the+ prefixed-id filter, because the controller decodes ids — the fault is+ not patched, it stops existing.+ 4. **Writes follow**, including the generic ones. The controller's+ `permitted_params` becomes the only writable-attribute list, so+ extension attributes work by construction and the hand-written lists+ go.+ 5. **The gaps become endpoints.** Product curation and the stock upsert+ are reached directly today; they become Admin API endpoints and the+ tools point at them. Credential filtering (`RecordSummary`) stays — it+ guards what leaves for a model, which is not the API's job.+ 6. **Delete what the dispatcher replaced.** The second scoping, the second+ permission check, the second error shape. The measure of this step is+ how much Ruby it removes.++7. **Later, outside this plan:** `spree mcp` stdio wrapper in `@spree/cli`+ that proxies to the mounted endpoint and prints client configs; a+ shopper-facing Storefront MCP (own plan). At 7 the catalog runs under+ TypeScript with `@spree/admin-sdk`, and the Ruby adapter is deleted+ rather than ported.### Taking the code from the assistant branch@@ -645,7 +796,9 @@ unaffected beyond the rebase.`git checkout feat/dash-assistant -- <path>` and `git mv` them into place,so blame follows the code; apply the three changes; run the moved specsunder `pnpm test:rspec core`.-2. Open the PR for step 1 alone. It is reviewable in isolation and has no+2. (Superseded 2026-09-16 by "Steps 1–5 ship as one pull request", and by+ step 6 shipping on the same branch before merge.) The original sequencing+ read: open the PR for step 1 alone. It is reviewable in isolation and has noMCP or LLM code in it.3. After it merges, rebase `feat/dash-assistant` onto `main`, delete themoved files from `spree/assistant`, point the RubyLLM adapter and@@ -679,25 +832,35 @@ and any later adapter inherit them rather than rediscovering them:## Constraints on Current Work+- **Do not add a tool that reads or writes a model directly (2026-10-10).**+ A tool names an Admin API operation. A capability with no endpoint is an+ endpoint to add first, not a reason to reach past it — the dashboard rule,+ applied to agents.+- **Do not copy a guard from a controller into the agent layer.** If the+ agent path needs it, the agent path is wrong: it should be running through+ the controller that already has it.+- **Do not add tool classes under `Spree::Assistant::Tools`** on theassistant 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 readsthem, 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 new back-office write is an Admin API operation, added to the catalog+ or to the exclusion list in the same PR.** The contract spec walks+ `admin.yaml`: every admin operation is either in the catalog or excluded+ with a reason, so a new endpoint cannot land unconsidered. Whether a+ service or a workflow sits behind it does not affect reachability.- **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.+ `update_workflow`**, never a hand-written action. A hand-written action+ loses the record-level `authorize_resource!` the base class performs, and+ a dispatched tool call inherits whatever the controller does — so this+ matters more now, not less.+- **An operation's request body is documented in OpenAPI** — that schema is+ what a tool offers a model, so an undocumented parameter is one no agent+ can use. Workflow YARD docs remain worth writing for their own readers;+ they no longer feed the tool schema, and the actor is injected by the+ controller from the credential rather than by the adapter.- **Keep `admin.yaml` regenerated after Admin API changes**; the writableschemas `describe_resource` returns come from it.- **Keep tool results compact.** A tool that returns a full admin payload by@@ -717,6 +880,13 @@ and any later adapter inherit them rather than rediscovering them:## Open Questions+- **Does the Admin API itself expose an invitation's `acceptance_url`?**+ `RecordSummary` withholds it from agents, and that is right — a link that+ mints a staff account should not reach an AI vendor. But if the endpoint+ returns it to any admin key, the agent filter is covering for an API that+ hands out a credential, and the fix belongs there. Worth a look on the API+ side, independently of this plan.+Nothing blocks implementation. One item is deliberately deferred:- **OAuth 2.1 for hosted consumer connectors** (claude.ai connectors,diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex d05f346e20..3438722062 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -8,6 +8,22 @@**Plan:** `6.0-uploads-and-file-ownership.md`.+## 2026-10-10: Agent tools run through the Admin API, not beside it++**Context:** The MCP branch (PR #14664) built its tools as a second way into the same data — their own store scoping, permission checks, Ransack call, writable-attribute lists and error shape, about 3,900 lines of Ruby. Probing the branch found three faults, all the same fault. A prefixed id filters nothing: `search_resources` calls `.ransack` directly and skips the controller step that decodes ids, so filtering variants by `product_id_eq: "prod_3uWpPTcf5W"` — the only form the tools return — answers 0 where the raw id answers 3, with no error. Extension attributes are invisible, because the writable list reads `resource_permitted_attributes` but not `additional_permitted_attributes`. And the stock upsert wrote to whichever shelf an id named, including another store's, because the scoping lived in its one caller.++**Decision:** A tool call runs the real Admin API request path — routing, authentication, controller, serializer, error format — dispatched in-process through `Rails.application.call` with the caller's own credential and `Host` header. No internal trusted header, which would rebuild the boundary this removes. No HTTP to itself: a socket back to the same app holds one Puma thread waiting on another, so concurrent tool calls on a small pool deadlock it.++`Spree::Current` does not reset across a nested dispatch — probed: an inner call overwrote the outer request's currency — so the adapter snapshots and restores it, with a spec proving a tool call cannot corrupt the MCP request's own state. Tool calls do not run inside a transaction the MCP controller opened.++The catalog is the lasting asset: each entry names an operation, a permission, a description and a parameter projection, with schemas from OpenAPI rather than Ruby signatures. A capability with no endpoint becomes an endpoint first — the rule the dashboard already follows.++Two simplifications follow. Generic create, update and destroy become correct for *every* resource, because the controller behind each runs whatever workflow it declares — the old rule that a resource with a workflow refuses the generic write existed only because those writes skipped workflows. That leaves dedicated tools for the non-CRUD member actions alone (cancel, complete, capture, fulfil, approve, activate). And the catalog is keyed by OpenAPI operation rather than by `Spree::Dependencies` key, so the contract spec walks `admin.yaml` instead of scanning controller source — and does not rest on a mechanism being replaced by workflow hooks.++Two operational notes recorded with it: the rate limiter counts the dispatched operations, not the MCP envelope, or one agent turn counts twice; and the adapter trims index responses until the Admin API has sparse fieldsets, since a full admin payload is more than a model's context should hold.++**Consequences:** Every guard added to the Admin API protects agents by construction. The prefixed-id fault stops existing rather than being patched, and the hand-written writable lists go. The branch loses more Ruby than it gains, which is the measure of the step. At 7 the same catalog runs under TypeScript with `@spree/admin-sdk`, differing only in which `fetch` it is given, so the Ruby adapter is deleted rather than ported. Credential filtering stays in the agent layer: guarding what leaves for a model is not the API's job.+## 2026-10-09: Typed filters keep sellers association-free, take arrays for `_in`, and ship no 5.x warning**Context:** List filters are being generated into OpenAPI and the SDKs from the Ransack allowlists, and PR C will reject unknown filters. Three choices fix what the published contract says before that happens.diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rbindex 151df5d48b..9767a2d056 100644--- a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb@@ -72,7 +72,7 @@ module Spree)end- result = Spree.stock_level_bulk_upsert_service.call(rows: rows)+ result = Spree.stock_level_bulk_upsert_workflow.call(store: current_store, rows: rows)render json: result.valueenddiff --git a/spree/core/app/services/spree/orders/create.rb b/spree/core/app/workflows/spree/orders/create.rbsimilarity index 92%rename from spree/core/app/services/spree/orders/create.rbrename to spree/core/app/workflows/spree/orders/create.rbindex f73cc3f18f..36997de837 100644--- a/spree/core/app/services/spree/orders/create.rb+++ b/spree/core/app/workflows/spree/orders/create.rb@@ -8,18 +8,18 @@ module Spree# Standalone from Spree::Carts::Create (storefront). Admin-created orders# are first-class Spree::Order records (status: 'draft') in 5.x and remain# so in 6.0 — Spree::Cart in 6.0 is storefront-only.- class Create- prepend Spree::ServiceModule::Base-+ class Create < Spree::Workflowattr_reader :discount_application_errors- # @param store [Spree::Store]- # @param customer [Object, nil] resolved customer (Spree.customer_class instance)- # @param created_by [Object, nil] the staff member creating the draft- # (Spree.admin_user_class instance); nil for machine callers (secret keys)- # @param params [Hash] order params (see admin API docs)+ # @param store [Spree::Store] the store the order belongs to+ # @param customer [Object, nil] who is ordering, when they are an+ # existing customer; the order keeps `email` either way+ # @param created_by [Object, nil] who is placing it — a staff member, or+ # the credential acting for one+ # @param params [Hash] the order's own attributes, plus `items`,+ # addresses and a coupon code# @return [Spree::ServiceModule::Result]- def call(store:, customer: nil, created_by: nil, params: {})+ def perform(store:, customer: nil, created_by: nil, params: {})@store = store@customer = customer@created_by = created_bydiff --git a/spree/core/app/services/spree/stock_levels/bulk_upsert.rb b/spree/core/app/workflows/spree/stock_levels/bulk_upsert.rbsimilarity index 53%rename from spree/core/app/services/spree/stock_levels/bulk_upsert.rbrename to spree/core/app/workflows/spree/stock_levels/bulk_upsert.rbindex 8a45fb63db..7d48e42587 100644--- a/spree/core/app/services/spree/stock_levels/bulk_upsert.rb+++ b/spree/core/app/workflows/spree/stock_levels/bulk_upsert.rb@@ -12,18 +12,22 @@ module Spree# A feed states absolute levels (+count_on_hand+), which is what an# external system knows. The movement records the delta between what Spree# held and what the feed says.- class BulkUpsert- prepend Spree::ServiceModule::Base+ class BulkUpsert < Spree::Workflow# What the stock history shows against a movement this service wrote.FEED_REASON = 'inventory_feed'.freeze- # @param rows [Array<Hash>] each with +variant_id+, +stock_location_id+,- # and either +count_on_hand+ (absolute) or +adjustment+ (relative);- # +backorderable+ optional+ # @param store [Spree::Store] whose shelves these are. Ids are resolved+ # through it, so a row naming another store's variant is not found+ # rather than written.+ # @param rows [Array<Hash>] one per shelf: +variant_id+ and+ # +stock_location_id+ naming it (prefixed ids, or raw), then either+ # +count_on_hand+ (the figure it should end at) or +adjustment+ (a+ # signed change); +backorderable+ optional# @return [Spree::ServiceModule::Result] +{ stock_level_count: N }+- def call(rows:)- rows = Array(rows).map { |row| row.with_indifferent_access }+ def perform(store:, rows:)+ @store = store+ rows = resolve(Array(rows).map { |row| row.with_indifferent_access })keyed = rows.select { |row| row[:variant_id].present? && row[:stock_location_id].present? }return success(stock_level_count: 0) if keyed.empty?@@ -41,6 +45,44 @@ module Spreeprivate+ # Names become this store's own ids, or nothing.+ #+ # Resolved here rather than by the caller, because a row reaching+ # `find_or_initialize_by` unscoped writes to whichever shelf the id+ # happens to name — including another merchant's. One caller decoding+ # ids correctly does not make the workflow safe for the next one.+ def resolve(rows)+ variants = scoped_ids(store_variants, Spree::Variant, rows.map { |row| row[:variant_id] })+ locations = scoped_ids(store_stock_locations, Spree::StockLocation,+ rows.map { |row| row[:stock_location_id] })++ rows.map do |row|+ row.merge(+ variant_id: variants[row[:variant_id]],+ stock_location_id: locations[row[:stock_location_id]]+ ).compact+ end+ end++ # Accepts a prefixed id or a raw one: the Admin API speaks prefixed,+ # while the importer and seeds hold records they already loaded.+ def scoped_ids(scope, model, values)+ decoded = values.compact.uniq.index_with do |value|+ model.decode_own_prefixed_id(value) || value+ end+ found = scope.where(id: decoded.values.compact).pluck(:id).map(&:to_s).to_set++ decoded.transform_values { |id| id if id && found.include?(id.to_s) }+ end++ def store_variants+ @store.variants+ end++ def store_stock_locations+ @store.stock_locations+ end+def apply_row(row)stock_level = Spree::StockLevel.find_or_initialize_by(variant_id: row[:variant_id], stock_location_id: row[:stock_location_id]diff --git a/spree/core/lib/spree/agent_tools/default_catalog.rb b/spree/core/lib/spree/agent_tools/default_catalog.rbindex 5c3467a2f3..6d593ba5a8 100644--- a/spree/core/lib/spree/agent_tools/default_catalog.rb+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb@@ -76,6 +76,7 @@ module Spree# Orders. `restock_items` is hidden: it is deprecated and ignored, so# offering it would invite a model to set something that does nothing.order_cancel_workflow: { permission: 'write_orders', except: %i[restock_items] },+ stock_level_bulk_upsert_workflow: 'write_stock',order_complete_workflow: 'write_orders',# Fulfillmentdiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex e91e43104b..6f6dc734f8 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -70,6 +70,11 @@ module Spreeorder_fee_create_service: 'Spree::Orders::Fees::Create',order_fee_update_service: 'Spree::Orders::Fees::Update',order_fee_destroy_service: 'Spree::Orders::Fees::Destroy',+ # A workflow since 6.0: its `perform` signature is what the agent+ # tools derive their schema from, which a service's opaque `params`+ # hash could not provide. The `_service` key still resolves it, so a+ # host app that overrode or called it keeps working.+ order_create_workflow: 'Spree::Orders::Create',order_create_service: 'Spree::Orders::Create',order_create_from_cart_service: 'Spree::Orders::CreateFromCart',order_update_service: 'Spree::Orders::Update',@@ -98,6 +103,10 @@ module Spree# inventory operationsstock_level_correct_service: 'Spree::StockLevels::Correct',+ # A workflow since 6.0: its signature is what the agent tool derives+ # its schema from, which `Spree::ServiceModule` could not provide.+ # The `_service` key still resolves it.+ stock_level_bulk_upsert_workflow: 'Spree::StockLevels::BulkUpsert',stock_level_bulk_upsert_service: 'Spree::StockLevels::BulkUpsert',stock_level_recount_service: 'Spree::StockLevels::Recount',stock_transfer_create_workflow: 'Spree::StockTransfers::Create',diff --git a/spree/core/spec/workflows/spree/stock_levels/bulk_upsert_spec.rb b/spree/core/spec/workflows/spree/stock_levels/bulk_upsert_spec.rbnew file mode 100644index 0000000000..71c70281e4--- /dev/null+++ b/spree/core/spec/workflows/spree/stock_levels/bulk_upsert_spec.rb@@ -0,0 +1,94 @@+require 'spec_helper'++RSpec.describe Spree::StockLevels::BulkUpsert do+ let(:store) { @default_store }+ let(:variant) { create(:variant) }+ let(:location) { store.stock_locations.first || create(:stock_location, store: store) }++ def level_for(variant, location, count)+ Spree::StockLevel.find_or_create_by!(variant: variant, stock_location: location) do |level|+ level.count_on_hand = count+ end+ end++ describe 'setting a figure' do+ it 'corrects the shelf to the count given' do+ level = level_for(variant, location, 5)++ result = described_class.call(store: store, rows: [+ { variant_id: variant.prefixed_id, stock_location_id: location.prefixed_id, count_on_hand: 40 }+ ])++ expect(result).to be_success+ expect(level.reload.count_on_hand).to eq(40)+ end++ it 'takes a raw id as well as a prefixed one' do+ level = level_for(variant, location, 5)++ described_class.call(store: store, rows: [+ { variant_id: variant.id, stock_location_id: location.id, count_on_hand: 12 }+ ])++ expect(level.reload.count_on_hand).to eq(12)+ end++ # Stock changes are recorded as movements so a merchant can see why a+ # figure changed; writing the column straight would leave a hole.+ it 'records the change as a movement' do+ level = level_for(variant, location, 5)++ expect {+ described_class.call(store: store, rows: [+ { variant_id: variant.prefixed_id, stock_location_id: location.prefixed_id, count_on_hand: 40 }+ ])+ }.to change { level.reload.stock_movements.count }.by(1)+ end+ end++ # The scoping lives here rather than in the one controller that used to do+ # it: a row reaching `find_or_initialize_by` unscoped writes to whichever+ # shelf the id names, including another merchant's.+ describe 'a row naming another store' do+ let(:other_store) { create(:store, code: "other-#{SecureRandom.hex(4)}") }++ it 'leaves their shelf alone' do+ theirs = create(:product, store: other_store).variants.first || create(:variant, product: create(:product, store: other_store))+ their_location = create(:stock_location, store: other_store)+ their_level = level_for(theirs, their_location, 7)++ result = described_class.call(store: store, rows: [+ { variant_id: theirs.prefixed_id, stock_location_id: their_location.prefixed_id, count_on_hand: 999 }+ ])++ expect(result).to be_success+ expect(result.value[:stock_level_count]).to eq(0)+ expect(their_level.reload.count_on_hand).to eq(7)+ end++ it 'applies the rows that are ours and skips the rest' do+ ours = level_for(variant, location, 1)+ theirs = create(:product, store: other_store).variants.first || create(:variant, product: create(:product, store: other_store))++ result = described_class.call(store: store, rows: [+ { variant_id: variant.prefixed_id, stock_location_id: location.prefixed_id, count_on_hand: 20 },+ { variant_id: theirs.prefixed_id, stock_location_id: location.prefixed_id, count_on_hand: 999 }+ ])++ expect(result.value[:stock_level_count]).to eq(1)+ expect(ours.reload.count_on_hand).to eq(20)+ end+ end++ describe 'nothing to do' do+ it 'succeeds with no rows' do+ expect(described_class.call(store: store, rows: [])).to be_success+ end++ it 'ignores a row naming no variant' do+ result = described_class.call(store: store, rows: [{ count_on_hand: 5 }])++ expect(result.value[:stock_level_count]).to eq(0)+ end+ end+end