Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Added a tool for which products a category, collection or price list holds

Damian Legawiec8610f1ed295c
diff --git a/docs/developer/agentic/admin-mcp.mdx b/docs/developer/agentic/admin-mcp.mdx
index 2de5585613..e8590c8eba 100644
--- a/docs/developer/agentic/admin-mcp.mdx
+++ b/docs/developer/agentic/admin-mcp.mdx
@@ -50,6 +50,7 @@ The tools are not a mirror of the API's endpoints — there would be hundreds, a
| Finding things | `describe_resource`, `search_resources`, `get_resource` | Discovering which resources exist and what they can be filtered by, then finding and reading records |
| Answering with numbers | `describe_reporting`, `query_report` | Revenue, orders and units, sliced by time, product, channel or country — the same figures the dashboard charts show |
| Doing things | One tool per operation: `orders_cancel`, `fulfillments_mark_delivered`, `products_activate`, `refunds_create`, `price_lists_activate` and around fifty more | Each runs the same workflow the dashboard runs, so validations, emails and webhooks behave identically |
+| Merchandising | `curate_products` | Which products a category, collection, catalog or price list holds |
| Store setup | `create_resource`, `update_resource`, `delete_resource` | Markets, channels, delivery and payment methods, tax rates and the rest of the settings screens |
An agent is only ever shown the tools its key permits, so the list stays small and relevant: a key minted for order operations sees around twenty.
diff --git a/spree/api/lib/spree/api/agent_membership_map.rb b/spree/api/lib/spree/api/agent_membership_map.rb
new file mode 100644
index 0000000000..125276b5b9
--- /dev/null
+++ b/spree/api/lib/spree/api/agent_membership_map.rb
@@ -0,0 +1,75 @@
+module Spree
+ module Api
+ # Which parents an agent may curate products into, derived from the
+ # controllers that adopt `Spree::Api::V3::Admin::ProductMembership`.
+ #
+ # Read off the controllers for the same reason {AgentResourceMap} is: a
+ # parent that adopts the concern later is curated without anyone editing
+ # this file, and one that drops it stops being offered.
+ module AgentMembershipMap
+ class << self
+ # @param map [Module]
+ # @return [Integer] how many parents were registered
+ def install(map: Spree::AgentTools::MembershipMap)
+ map.reset!
+
+ curating_controllers.each do |controller|
+ target = target_for(controller)
+ next if target.blank?
+
+ # Addressing a parent an agent cannot otherwise read would hand it
+ # a write with no matching read, and no way to name what it changed.
+ entry = Spree::AgentTools::ResourceMap.find(target.pluralize)
+ next if entry.nil?
+
+ map.register(
+ target: target,
+ model_name: entry.model_name,
+ permission: write_permission_for(entry),
+ positioned: controller.method_defined?(:reposition),
+ service_namespace: service_namespace_for(target)
+ )
+ end
+
+ map.all.size
+ end
+
+ private
+
+ def curating_controllers
+ Rails.application.eager_load! unless Rails.application.config.eager_load
+
+ Spree::Api::V3::Admin::ResourceController.descendants.
+ select { |controller| controller.include?(Spree::Api::V3::Admin::ProductMembership) }.
+ sort_by(&:name)
+ end
+
+ # Curating is a write to the parent, so it is gated on the parent's
+ # own write scope — a price list rides `write_products`, a category
+ # `write_categories`, exactly as their controllers do.
+ def write_permission_for(entry)
+ entry.write_permission.presence || "write_#{entry.permission.to_s.sub(/\Aread_/, '')}"
+ end
+
+ # `Admin::Categories::ProductsController` curates a category. The
+ # parent is the namespace the nested controller sits in, which is how
+ # the routes name it too.
+ def target_for(controller)
+ controller.name.to_s.split('::')[-2]&.underscore&.singularize
+ end
+
+ # A parent whose curation goes through a service has one named for it
+ # — `Spree::Categories::AddProducts`, which publishes events and
+ # reindexes. The others write the join row from the model. Probed
+ # rather than listed, so a parent that gains a service is followed.
+ def service_namespace_for(target)
+ namespace = "Spree::#{target.camelize.pluralize}"
+ return unless "#{namespace}::AddProducts".safe_constantize
+ return unless "#{namespace}::RemoveProducts".safe_constantize
+
+ namespace
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/lib/spree/api/engine.rb b/spree/api/lib/spree/api/engine.rb
index b462e0a4fa..428dff8ea2 100644
--- a/spree/api/lib/spree/api/engine.rb
+++ b/spree/api/lib/spree/api/engine.rb
@@ -4,6 +4,7 @@ require_relative 'dependencies'
require_relative 'configuration'
require_relative 'agent_write_schemas'
require_relative 'agent_resource_map'
+require_relative 'agent_membership_map'
require_relative 'oauth'
module Spree
diff --git a/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb b/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb
new file mode 100644
index 0000000000..40e26eef5a
--- /dev/null
+++ b/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb
@@ -0,0 +1,134 @@
+require 'spec_helper'
+
+# Merchandising is largely membership, so this is one of the writes a merchant
+# asks for most. It runs over every parent the Admin API exposes its nested
+# products surface for, derived rather than listed.
+RSpec.describe 'agent product curation' do
+ let(:store) { @default_store }
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+
+ def tool(ctx = context)
+ Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'curate_products' }
+ end
+
+ describe 'the derived set of parents' do
+ # A parent that adopts the membership concern should be curated without
+ # anyone editing a list, which is the whole reason the map is derived.
+ it 'covers every parent the Admin API curates products for' do
+ expect(Spree::AgentTools::MembershipMap.targets).to include('category', 'collection', 'catalog', 'price_list')
+ end
+
+ it 'gates each one on its own write permission' do
+ expect(Spree::AgentTools::MembershipMap.find('category').permission).to eq('write_categories')
+ expect(Spree::AgentTools::MembershipMap.find('collection').permission).to eq('write_collections')
+ end
+ end
+
+ describe 'adding and removing' do
+ let(:category) { create(:category, store: store) }
+ let(:product) { create(:product, store: store) }
+
+ it 'adds a product and reports what changed' do
+ result = tool.call(target: 'category', id: category.prefixed_id, products: [product.prefixed_id])
+
+ expect(result[:error]).to be_nil
+ expect(result[:added]).to eq(1)
+ expect(category.reload.products).to include(product)
+ end
+
+ # The count is read back from membership rather than taken from the
+ # input, so a product already there is reported as such instead of
+ # counted a second time.
+ it 'reports a product that was already a member' do
+ tool.call(target: 'category', id: category.prefixed_id, products: [product.prefixed_id])
+ result = tool.call(target: 'category', id: category.prefixed_id, products: [product.prefixed_id])
+
+ expect(result[:added]).to eq(0)
+ expect(result[:already_present]).to eq(1)
+ end
+
+ it 'removes a product' do
+ tool.call(target: 'category', id: category.prefixed_id, products: [product.prefixed_id])
+ result = tool.call(target: 'category', id: category.prefixed_id,
+ products: [product.prefixed_id], operation: 'remove')
+
+ expect(result[:removed]).to eq(1)
+ expect(category.reload.products).not_to include(product)
+ end
+
+ it 'reports a product that was never a member' do
+ result = tool.call(target: 'category', id: category.prefixed_id,
+ products: [product.prefixed_id], operation: 'remove')
+
+ expect(result[:removed]).to eq(0)
+ expect(result[:not_a_member]).to eq(1)
+ end
+ end
+
+ describe 'refusals' do
+ let(:category) { create(:category, store: store) }
+ let(:product) { create(:product, store: store) }
+
+ it 'names the parents it can curate when given one it cannot' do
+ result = tool.call(target: 'shelf', id: category.prefixed_id, products: [product.prefixed_id])
+
+ expect(result[:error]).to include('shelf')
+ expect(result[:available_targets]).to include('category')
+ end
+
+ # The server promises that a tool a caller cannot see is one the store has
+ # not granted, so a write offered to a read-only grant breaks that promise.
+ it 'is not offered to a caller who can curate nothing' do
+ read_only = create(:api_key, :secret, store: store, scopes: %w[read_categories read_products])
+ read_context = Spree::AgentTools::Context.new(store: store, api_key: read_only)
+
+ expect(tool(read_context)).to be_nil
+ end
+
+ # A caller correcting itself should not pick a parent it will then be
+ # refused for.
+ it 'names only the parents the caller may curate' do
+ partial = create(:api_key, :secret, store: store, scopes: %w[write_categories read_products])
+ partial_context = Spree::AgentTools::Context.new(store: store, api_key: partial)
+
+ result = tool(partial_context).call(target: 'shelf', id: category.prefixed_id,
+ products: [product.prefixed_id])
+
+ expect(result[:available_targets]).to include('category')
+ expect(result[:available_targets]).not_to include('collection')
+ end
+
+ it 'refuses a caller holding only the read permission' do
+ elsewhere = create(:api_key, :secret, store: store, scopes: %w[write_collections read_categories read_products])
+ limited = Spree::AgentTools::Context.new(store: store, api_key: elsewhere)
+
+ result = tool(limited).call(target: 'category', id: category.prefixed_id,
+ products: [product.prefixed_id])
+
+ expect(result[:error]).to include('permission')
+ expect(category.reload.products).to be_empty
+ end
+
+ # The parent is looked up through the store's own scope, so another
+ # store's category is not found rather than quietly curated.
+ it 'cannot reach a parent belonging to another store' do
+ other_category = create(:category, store: create(:store))
+
+ result = tool.call(target: 'category', id: other_category.prefixed_id,
+ products: [product.prefixed_id])
+
+ expect(result[:error]).to include('No category found')
+ expect(other_category.reload.products).to be_empty
+ end
+
+ it 'ignores a product id that names nothing in this store' do
+ foreign = create(:product, store: create(:store))
+
+ result = tool.call(target: 'category', id: category.prefixed_id, products: [foreign.prefixed_id])
+
+ expect(result[:error]).to include('name a product in this store')
+ expect(category.reload.products).to be_empty
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/curate_products.rb b/spree/core/app/tools/spree/agent_tools/curate_products.rb
new file mode 100644
index 0000000000..5116f9bd7e
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/curate_products.rb
@@ -0,0 +1,146 @@
+module Spree
+ module AgentTools
+ # Puts products into a category, collection, catalog or price list, and
+ # takes them out again.
+ #
+ # Merchandising is largely membership — what sits in which category, what
+ # a wholesale catalog carries, what a price list prices — so this is one
+ # of the writes a merchant asks for most. One tool over every curating
+ # parent, derived from the membership map, because the Admin API gives
+ # them all one nested surface and a parent that adopts it later should
+ # need no new tool.
+ class CurateProducts < Spree::AgentTool
+ tool_name 'curate_products'
+ description 'Add products to a category, collection, catalog or price list, or remove ' \
+ 'them. Find the parent and the products with search_resources first and pass ' \
+ 'their ids. Ids naming nothing in this store are ignored, and the result ' \
+ 'says how many memberships actually changed.'
+ # Gated per parent in `call`: curating a category needs
+ # write_categories and a price list write_products, so a class-level
+ # key would hide the tool from a caller holding one but not the other.
+ permission nil
+ mutating!
+
+ param :target, description: 'What to curate: category, collection, catalog or price_list',
+ required: true
+ param :id, description: "The parent's prefixed id, as it appears in search results",
+ required: true
+ param :products, type: :array, items: :string,
+ description: 'Prefixed ids of the products to add or remove', required: true
+ param :operation, description: '"add" (the default) or "remove"'
+
+ # Offered only to a caller who can curate at least one parent.
+ #
+ # The class declares no permission, because each parent carries its own
+ # — but without this a read-only grant was shown a write it could never
+ # use, which is exactly the "a tool you cannot see is one this store has
+ # not granted" promise the server makes in its instructions.
+ def permitted?
+ MembershipMap.all.any? { |entry| context.holds?(entry.permission) }
+ end
+
+ def call(target:, id:, products:, operation: nil)
+ entry = MembershipMap.find(target)
+ return unknown_target(target) if entry.nil?
+ return forbidden(entry) unless context.holds?(entry.permission)
+
+ parent = find_parent(entry, id)
+ return missing_parent(entry, id) if parent.nil?
+
+ # The scope check answers tenancy; this answers which records within
+ # it — a role that may edit only its own categories cannot curate
+ # another's, the same two steps the controller takes.
+ refusal = unauthorized(:update, parent)
+ return refusal if refusal
+
+ records = find_products(products)
+ return no_products if records.empty?
+
+ removing?(operation) ? remove(entry, parent, records) : add(entry, parent, records)
+ end
+
+ def summary(arguments)
+ count = Array(arguments[:products]).size
+ noun = 'product'.pluralize(count)
+ parent = arguments[:target].to_s.tr('_', ' ')
+
+ if removing?(arguments[:operation])
+ "Remove #{count} #{noun} from #{parent} #{arguments[:id]}"
+ else
+ "Add #{count} #{noun} to #{parent} #{arguments[:id]}"
+ end
+ end
+
+ private
+
+ def removing?(operation)
+ operation.to_s.casecmp('remove').zero?
+ end
+
+ # Counted by re-reading membership rather than by trusting the input: a
+ # product already a member changes nothing, and the merchant is told
+ # what actually happened rather than what was asked for.
+ def add(entry, parent, records)
+ before = member_ids(parent, records)
+ entry.add(parent, records.reject { |record| before.include?(record.id) })
+ gained = member_ids(parent, records) - before
+
+ { ok: true, target: entry.target, id: parent.prefixed_id,
+ added: gained.size, already_present: before.size }
+ end
+
+ def remove(entry, parent, records)
+ before = member_ids(parent, records)
+ entry.remove(parent, records.select { |record| before.include?(record.id) })
+ lost = before - member_ids(parent, records)
+
+ { ok: true, target: entry.target, id: parent.prefixed_id,
+ removed: lost.size, not_a_member: records.size - before.size }
+ end
+
+ def member_ids(parent, records)
+ parent.products.where(id: records.map(&:id)).reorder(nil).distinct.pluck(:id).to_set
+ end
+
+ def find_parent(entry, id)
+ context.accessible(entry.model_class.for_store(context.store), :update).find_by_prefix_id(id)
+ end
+
+ # An id naming nothing is dropped rather than refused, which is what the
+ # Admin API's own bulk writes do — the counts are what tell the merchant
+ # which ones landed.
+ def find_products(ids)
+ decoded = Array(ids).filter_map do |id|
+ Spree::Product.decode_prefixed_id(id) if Spree::PrefixedId.prefixed_id?(id.to_s)
+ end
+ return [] if decoded.empty?
+
+ context.accessible(Spree::Product.for_store(context.store), :update).where(id: decoded).to_a
+ end
+
+ # Only the parents this caller can actually curate, so a model
+ # correcting itself does not pick one it will then be refused.
+ def unknown_target(target)
+ allowed = MembershipMap.all.select { |entry| context.holds?(entry.permission) }.map(&:target).sort
+
+ { error: "Cannot curate #{target.inspect}.", available_targets: allowed }
+ end
+
+ def forbidden(entry)
+ { error: "You do not have permission to change which products a #{label(entry)} holds." }
+ end
+
+ def missing_parent(entry, id)
+ { error: "No #{label(entry)} found for #{id.inspect}." }
+ end
+
+ def no_products
+ { error: 'None of those ids name a product in this store.' }
+ end
+
+ def label(entry)
+ entry.target.tr('_', ' ')
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools.rb b/spree/core/lib/spree/agent_tools.rb
index deda5031f9..fe1bad5fce 100644
--- a/spree/core/lib/spree/agent_tools.rb
+++ b/spree/core/lib/spree/agent_tools.rb
@@ -1,6 +1,7 @@
require 'spree/agent_tools/registry'
require 'spree/agent_tools/context'
require 'spree/agent_tools/resource_map'
+require 'spree/agent_tools/membership_map'
require 'spree/agent_tools/record_summary'
require 'spree/agent_tools/workflow_schema'
require 'spree/agent_tools/workflow_tool'
diff --git a/spree/core/lib/spree/agent_tools/default_catalog.rb b/spree/core/lib/spree/agent_tools/default_catalog.rb
index 2d6b9abf8a..3e087e4700 100644
--- a/spree/core/lib/spree/agent_tools/default_catalog.rb
+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb
@@ -19,6 +19,7 @@ module Spree
Spree::AgentTools::CreateResource
Spree::AgentTools::UpdateResource
Spree::AgentTools::DeleteResource
+ Spree::AgentTools::CurateProducts
Spree::AgentTools::QueryReport
Spree::AgentTools::DescribeReporting
Spree::AgentTools::CreateExport
diff --git a/spree/core/lib/spree/agent_tools/membership_map.rb b/spree/core/lib/spree/agent_tools/membership_map.rb
new file mode 100644
index 0000000000..c972bdb918
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/membership_map.rb
@@ -0,0 +1,102 @@
+module Spree
+ module AgentTools
+ # The parents a product can belong to: categories, collections, catalogs,
+ # price lists — whatever the Admin API exposes its nested products
+ # surface for.
+ #
+ # A contract like {ResourceMap}: core declares the shape, and `spree_api`
+ # fills it from the controllers that adopt the membership concern, so a
+ # parent that adopts it later is curated without a new tool.
+ module MembershipMap
+ Entry = Struct.new(:target, :model_name, :permission, :positioned, :service_namespace,
+ keyword_init: true) do
+ # @return [Class]
+ def model_class
+ model_name.constantize
+ end
+
+ # Whether members carry an order the merchant arranged by hand.
+ def positioned?
+ positioned.present?
+ end
+
+ # Adds products to this parent, the way its own controller does.
+ #
+ # Two shapes exist and both are the controller's: a curation service
+ # for the parents that publish events and reindex, a model method for
+ # the ones that write a join row. Carried here so the tool never has
+ # to know which parent it is holding.
+ def add(parent, products)
+ return if products.empty?
+
+ if service_namespace
+ "#{service_namespace}::AddProducts".constantize.call(service_key => [parent], products: products)
+ else
+ parent.add_products(products.map(&:id))
+ end
+ end
+
+ def remove(parent, products)
+ return if products.empty?
+
+ if service_namespace
+ "#{service_namespace}::RemoveProducts".constantize.call(service_key => [parent], products: products)
+ else
+ parent.remove_products(products.map(&:id))
+ end
+ end
+
+ # `Spree::Categories::AddProducts` takes `categories:`.
+ def service_key
+ target.pluralize.to_sym
+ end
+ end
+
+ class << self
+ # @return [Array<Entry>]
+ def all
+ derive!
+ entries.values
+ end
+
+ # @param target [String, Symbol] 'category', 'price_list', …
+ # @return [Entry, nil]
+ def find(target)
+ derive!
+ entries[target.to_s]
+ end
+
+ # @return [Array<String>]
+ def targets
+ all.map(&:target).sort
+ end
+
+ def register(target:, model_name:, permission:, positioned: false, service_namespace: nil)
+ entries[target.to_s] = Entry.new(target: target.to_s, model_name: model_name,
+ permission: permission, positioned: positioned,
+ service_namespace: service_namespace)
+ end
+
+ def reset!
+ @entries = {}
+ end
+
+ # Filled on first read rather than at boot: deriving it loads every
+ # admin controller, and a developer who never runs an agent should
+ # not pay that on each code reload.
+ def derive!
+ return if @derived
+
+ @derived = true
+ Spree::Api::AgentMembershipMap.install if defined?(Spree::Api::AgentMembershipMap)
+ end
+
+ private
+
+ def entries
+ @entries ||= {}
+ end
+ end
+ end
+ end
+end
diff --git a/spree/mcp/lib/spree/mcp/server.rb b/spree/mcp/lib/spree/mcp/server.rb
index e96b8384d4..6f23484bd0 100644
--- a/spree/mcp/lib/spree/mcp/server.rb
+++ b/spree/mcp/lib/spree/mcp/server.rb
@@ -20,6 +20,10 @@ module Spree
orders, units — use describe_reporting and then query_report rather than
counting records yourself.
+ Which products a category, collection, catalog or price list holds is
+ curate_products — merchandising is mostly membership, and that one tool
+ covers every one of those parents.
+
Writes are named after what they do: a tool per operation, each running
the same workflow the dashboard runs, so validations and notifications
behave identically. Record arguments are prefixed ids as they appear in
diff --git a/spree/mcp/lib/spree/mcp/tool_adapter.rb b/spree/mcp/lib/spree/mcp/tool_adapter.rb
index 87b59652ed..8a9924e2aa 100644
--- a/spree/mcp/lib/spree/mcp/tool_adapter.rb
+++ b/spree/mcp/lib/spree/mcp/tool_adapter.rb
@@ -61,6 +61,12 @@ module Spree
# comes back as a tool error rather than a protocol error, which the
# model never sees.
#
+ # A refusal carries more than its message: the resources that do
+ # exist, the fields that can be filtered, the import's own column
+ # names. Forwarding only `:error` threw all of that away, so a model
+ # told "Unknown filter(s): notreal_eq" had to guess again instead of
+ # reading the list the tool had already computed.
+ #
# Public because the definition block calls it through a closure.
#
# @param tool [Spree::AgentTool]
@@ -70,7 +76,7 @@ module Spree
result = tool.call(**arguments.symbolize_keys.except(:server_context))
if result.is_a?(Hash) && result[:error].present?
- ::MCP::Tool::Response.new([{ type: 'text', text: result[:error].to_s }], error: true)
+ ::MCP::Tool::Response.new([{ type: 'text', text: refusal_text(result) }], error: true)
else
::MCP::Tool::Response.new([{ type: 'text', text: text_for(result) }], structured_content: result)
end
@@ -108,6 +114,17 @@ module Spree
#
# A count is a description of an answer, never the answer. The only
# text that may stand in for a payload is one the tool wrote itself.
+ # The message, then whatever the refusal offered to correct it with.
+ #
+ # @param result [Hash]
+ # @return [String]
+ def refusal_text(result)
+ hints = result.except(:error).compact_blank
+ return result[:error].to_s if hints.empty?
+
+ "#{result[:error]}\n#{JSON.generate(hints)}"
+ end
+
def text_for(result)
return result.to_s unless result.is_a?(Hash)
diff --git a/spree/mcp/spec/lib/spree/mcp/server_spec.rb b/spree/mcp/spec/lib/spree/mcp/server_spec.rb
index 400f55afaf..24fbb19f45 100644
--- a/spree/mcp/spec/lib/spree/mcp/server_spec.rb
+++ b/spree/mcp/spec/lib/spree/mcp/server_spec.rb
@@ -211,6 +211,20 @@ RSpec.describe Spree::Mcp::Server do
expect(response.dig('result', 'content').first['text']).to include('prod_missing')
end
+ # A refusal carries what the model needs to correct itself — the fields
+ # that can be filtered, the resources that exist. Forwarding only the
+ # message left the model guessing at a list the tool had already built.
+ it 'carries the correction hints a refusal computed' do
+ response = call('tools/call', name: 'search_resources',
+ arguments: { 'resource' => 'products', 'filters' => { 'notreal_eq' => 'x' } })
+ text = response.dig('result', 'content').first['text']
+
+ expect(response.dig('result', 'isError')).to be(true)
+ expect(text).to include('notreal_eq')
+ expect(text).to include('filterable_fields')
+ expect(text).to include('name')
+ end
+
it 'refuses an id belonging to another store' do
other_product = create(:product, store: create(:store, code: "other-#{SecureRandom.hex(4)}"), name: 'Not Ours')