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.

Move the agent-tool registry into spree_core

Damian Legawiec1ec9beb4ef7a
diff --git a/spree/core/app/tools/spree/agent_tools/create_export.rb b/spree/core/app/tools/spree/agent_tools/create_export.rb
new file mode 100644
index 0000000000..ba4a702044
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/create_export.rb
@@ -0,0 +1,87 @@
+module Spree
+ module AgentTools
+ # Exports records to a CSV the merchant can download.
+ #
+ # Mutating not because it changes the store — it does not — but because
+ # it produces a file of store data and emails a link to it. That leaves
+ # the building, so a merchant decides, not the model.
+ class CreateExport < Spree::AgentTool
+ tool_name 'create_export'
+ description 'Export records to a CSV file. Say which kind of records and, ' \
+ 'optionally, the same filters search_resources accepts. The merchant ' \
+ 'approves before the file is generated.'
+ # Exports are gated on the READ scope of what is being exported — the
+ # Admin API treats an export as a read, because that is what it is.
+ # Checked per resource in `call`, since exporting orders and exporting
+ # products are different permissions.
+ permission 'read_products'
+ mutating!
+
+ param :resource, description: 'What to export: products, orders, customers, gift_cards',
+ required: true
+ param :filters, type: :object,
+ description: 'Optional Ransack filters, e.g. {"status_eq": "active"}'
+
+ def call(resource:, filters: nil)
+ export_class = export_class_for(resource)
+ return unknown_resource(resource) if export_class.nil?
+
+ required = "read_#{export_class.required_scope}"
+ unless context.permitted?(required)
+ return { error: "You do not have permission to export #{resource.to_s.tr('_', ' ')}." }
+ end
+
+ export = export_class.new(
+ store: context.store,
+ # The export builds its own ability from this user, so the file
+ # contains exactly the records that admin could see — record-level
+ # rules included.
+ user: context.user,
+ format: 'csv',
+ search_params: filters.presence
+ )
+
+ refusal = unauthorized(:create, export)
+ return refusal if refusal
+
+ # Saving publishes `export.created`, which is what actually enqueues
+ # generation. (`generate_async` hands a raw id to a job that expects a
+ # prefixed one — the subscriber is the working path.)
+ return { error: export.errors.full_messages.to_sentence } unless export.save
+
+ {
+ ok: true,
+ id: export.prefixed_id,
+ resource: resource.to_s,
+ message: 'The export is being prepared; it will appear under Settings → Exports.'
+ }
+ end
+
+ def summary(arguments)
+ label = arguments[:resource].to_s.tr('_', ' ')
+ return "Export all #{label}" if arguments[:filters].blank?
+
+ filters = arguments[:filters].keys.map { |key| key.to_s.tr('_', ' ') }.join(', ')
+ "Export #{label} filtered by #{filters}"
+ end
+
+ private
+
+ # Only the export kinds Spree actually ships, resolved by name rather
+ # than constantized from model input.
+ def export_class_for(resource)
+ key = resource.to_s.downcase
+ Spree::Export.descendants.find do |klass|
+ klass.name.demodulize.underscore == key
+ end
+ end
+
+ def unknown_resource(resource)
+ {
+ error: "Cannot export #{resource.inspect}",
+ available: Spree::Export.descendants.map { |k| k.name.demodulize.underscore }.sort
+ }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/create_resource.rb b/spree/core/app/tools/spree/agent_tools/create_resource.rb
new file mode 100644
index 0000000000..f966f98952
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/create_resource.rb
@@ -0,0 +1,40 @@
+module Spree
+ module AgentTools
+ # Creates a record of a resource the Admin API writes directly.
+ class CreateResource < Spree::AgentTools::ResourceWrite
+ tool_name 'create_resource'
+ description 'Create a store setup record — a market, channel, delivery method, payment ' \
+ 'method, tax rate and so on. Call describe_resource first for the attributes ' \
+ 'a resource accepts. Catalog and order records are created by their own tools.'
+
+ param :resource, description: 'Resource key — call describe_resource for the list', required: true
+ param :attributes, type: :object, description: 'Attributes to set on the new record', required: true
+
+ def call(resource:, attributes: {})
+ entry, refusal = writable_entry(resource)
+ return refusal if refusal
+
+ permitted, rejection = permitted_attributes(entry, attributes)
+ return rejection if rejection
+
+ record = build_record(entry, permitted)
+ return { error: "You do not have permission to create this #{entry.key.singularize}." } unless context.can?(:create, record)
+
+ save_record(entry, record)
+ end
+
+ private
+
+ # Built through the store's own association where there is one, so the
+ # record carries its tenancy from where it was built rather than from an
+ # attribute assigned afterwards — the same rule the API's build_resource
+ # follows.
+ def build_record(entry, attributes)
+ association = entry.key.to_sym
+ scope = context.store.respond_to?(association) ? context.store.public_send(association) : entry.model_class
+
+ scope.new(attributes)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/delete_resource.rb b/spree/core/app/tools/spree/agent_tools/delete_resource.rb
new file mode 100644
index 0000000000..9cae340ac6
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/delete_resource.rb
@@ -0,0 +1,30 @@
+module Spree
+ module AgentTools
+ # Removes a record of a resource the Admin API deletes directly.
+ class DeleteResource < Spree::AgentTools::ResourceWrite
+ tool_name 'delete_resource'
+ description 'Delete a store setup record. Catalog and order records are removed by their ' \
+ 'own tools, which run the workflow the dashboard runs.'
+
+ param :resource, description: 'Resource key — call describe_resource for the list', required: true
+ param :id, description: 'The record id as shown in search results', required: true
+
+ def call(resource:, id:)
+ entry, refusal = writable_entry(resource)
+ return refusal if refusal
+
+ record = entry.scope_for(context, :destroy).find_by_prefix_id(id)
+ return { error: "No #{entry.key.singularize} found for #{id.inspect}." } if record.nil?
+ return { error: "You do not have permission to delete this #{entry.key.singularize}." } unless context.can?(:destroy, record)
+
+ label = RecordSummary.call(entry: entry, record: record)[:title]
+
+ if record.destroy
+ { summary: "Delete #{entry.key.singularize.humanize.downcase} #{label}" }
+ else
+ { error: record.errors.full_messages.to_sentence.presence || "#{label} could not be deleted." }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/describe_import_mapping.rb b/spree/core/app/tools/spree/agent_tools/describe_import_mapping.rb
new file mode 100644
index 0000000000..d3352cfc7c
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/describe_import_mapping.rb
@@ -0,0 +1,75 @@
+module Spree
+ module AgentTools
+ # What an import still needs mapped: the file's own column headings, the
+ # Spree fields available, and which of those are required.
+ #
+ # This is the half of the mapping problem a computer cannot do. Deciding
+ # that a column headed "Retail Price (inc VAT)" is the price field is
+ # judgement about messy human spreadsheets — exactly what the model is
+ # for — but it can only judge from the real vocabulary, so this hands it
+ # the schema rather than letting it guess field names.
+ class DescribeImportMapping < Spree::AgentTool
+ tool_name 'describe_import_mapping'
+ description "List an import's unmapped file columns and the Spree fields they can " \
+ 'map onto, so you can propose a mapping. Call this before ' \
+ 'propose_import_mapping.'
+ permission 'read_settings'
+
+ param :id, description: 'Import id or number. Omit for the most recent import awaiting mapping.',
+ required: false
+
+ def call(id: nil)
+ import = find_import(id)
+ return { error: 'No import is waiting to be mapped.' } if import.nil?
+
+ {
+ id: import.prefixed_id,
+ number: import.number,
+ status: import.status,
+ file_columns: import.csv_headers,
+ unmapped_file_columns: import.unmapped_file_columns,
+ spree_fields: describe_fields(import),
+ already_mapped: current_mapping(import),
+ sample_row: import.sample_row
+ }.compact
+ end
+
+ def summary(arguments)
+ 'Read the import file layout'
+ end
+
+ private
+
+ def find_import(id)
+ scope = Spree::AgentTools::ResourceMap.find('imports').scope_for(context)
+ return scope.where(status: 'mapping').order(created_at: :desc).first if id.blank?
+
+ scope.find_by_prefix_id(id) || scope.find_by(number: id)
+ rescue ArgumentError, NoMethodError
+ scope.find_by(number: id)
+ end
+
+ # Name, human label and whether it must be filled — the model needs all
+ # three to explain its choices and to know what it cannot leave out.
+ def describe_fields(import)
+ schema = import.import_schema
+ return [] if schema.nil?
+
+ schema.fields.map do |field|
+ {
+ field: field[:name],
+ label: field[:label],
+ required: field[:required] == true
+ }
+ end
+ end
+
+ def current_mapping(import)
+ mapped = import.mappings.mapped
+ return if mapped.empty?
+
+ mapped.to_h { |mapping| [mapping.schema_field, mapping.file_column] }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/describe_reporting.rb b/spree/core/app/tools/spree/agent_tools/describe_reporting.rb
new file mode 100644
index 0000000000..a02ccfd178
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/describe_reporting.rb
@@ -0,0 +1,39 @@
+module Spree
+ module AgentTools
+ # Tells the model which metrics and dimensions this store can be asked
+ # about, so it composes a query from the real vocabulary rather than
+ # guessing names and reading errors back to the merchant.
+ class DescribeReporting < Spree::AgentTool
+ tool_name 'describe_reporting'
+ description 'List the reporting metrics and dimensions available, and which dimensions ' \
+ 'each metric can be grouped by. Call this before query_report.'
+ permission 'read_reports'
+
+ def call
+ Spree::Reporting::Schema.new(
+ store: context.store,
+ allowed: ->(member) { allowed?(member) }
+ ).to_h
+ end
+
+ def summary(_arguments)
+ 'List the reporting metrics and dimensions'
+ end
+
+ private
+
+ # Filtered to what this caller may reference, so the model is never
+ # offered a member its next query would be refused for. The same
+ # predicate the reporting schema endpoint applies, in the same two
+ # flavours: a subject through CanCanCan for an admin, a key scope for a
+ # secret key.
+ def allowed?(member)
+ if context.user_principal?
+ member.subject.nil? || context.can?(:read, member.subject.call)
+ else
+ member.key_scope.blank? || context.api_key.has_scope?(member.key_scope)
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/describe_resource.rb b/spree/core/app/tools/spree/agent_tools/describe_resource.rb
new file mode 100644
index 0000000000..e7985e378a
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/describe_resource.rb
@@ -0,0 +1,47 @@
+module Spree
+ module AgentTools
+ # Tells the model which resources exist and what they can be filtered by,
+ # so it discovers the real vocabulary instead of guessing field names and
+ # producing errors the merchant has to read.
+ class DescribeResource < Spree::AgentTool
+ tool_name 'describe_resource'
+ description 'List the store resources you can search, and the fields each one ' \
+ 'can be filtered and sorted by. Call this before search_resources ' \
+ 'if you are unsure which filter to use.'
+ # Deliberately ungated: it exposes only field names, and the resources it
+ # lists are already filtered to what this admin may read.
+ permission nil
+
+ param :resource,
+ description: 'Optional resource key to describe. Omit to list them all.',
+ required: false
+
+ def call(resource: nil)
+ entries = Spree::AgentTools::ResourceMap.available_for(context)
+ entries = entries.select { |entry| entry.key == resource.to_s } if resource.present?
+
+ if entries.empty?
+ return { error: "Unknown or unavailable resource #{resource.inspect}",
+ available: Spree::AgentTools::ResourceMap.available_for(context).map(&:key) }
+ end
+
+ { resources: entries.map { |entry| describe(entry) } }
+ end
+
+ private
+
+ def describe(entry)
+ {
+ resource: entry.key,
+ filterable_fields: entry.filterable_fields,
+ # Named queries answer things no column can — stock levels live
+ # across warehouses, so "out of stock" is a scope, not a field.
+ filterable_scopes: entry.filterable_scopes,
+ usage: 'Attribute filters use Ransack predicates, e.g. name_cont, created_at_gteq, ' \
+ 'status_eq. Named scopes are passed as a bare key set to true, e.g. ' \
+ '{"out_of_stock": true}.'
+ }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/get_import_status.rb b/spree/core/app/tools/spree/agent_tools/get_import_status.rb
new file mode 100644
index 0000000000..45a330361b
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/get_import_status.rb
@@ -0,0 +1,68 @@
+module Spree
+ module AgentTools
+ # Where an import has got to, and what went wrong with it.
+ #
+ # A merchant who uploaded a file wants one of two answers: is it done, or
+ # why did those rows fail? Both are tedious to assemble from the imports
+ # page and easy to say in a sentence.
+ class GetImportStatus < Spree::AgentTool
+ FAILED_ROW_SAMPLE = 5
+
+ tool_name 'get_import_status'
+ description 'Check how an import is going: its state, how many rows succeeded ' \
+ 'or failed, and why the failures failed.'
+ permission 'read_settings'
+
+ param :id, description: 'Import id or number. Omit for the most recent import.',
+ required: false
+
+ def call(id: nil)
+ import = find_import(id)
+ return { error: 'No import found.' } if import.nil?
+
+ {
+ id: import.prefixed_id,
+ number: import.number,
+ type: import_kind(import),
+ status: import.status,
+ rows: import.rows_status_counts,
+ # The reasons, not the rows: a merchant fixes a spreadsheet by
+ # learning "12 rows have no SKU", not by reading 12 rows back.
+ failure_reasons: failure_reasons(import)
+ }.compact
+ end
+
+ def summary(arguments)
+ arguments[:id].present? ? "Check import #{arguments[:id]}" : 'Check the latest import'
+ end
+
+ private
+
+ def find_import(id)
+ scope = Spree::AgentTools::ResourceMap.find('imports').scope_for(context)
+ return scope.order(created_at: :desc).first if id.blank?
+
+ scope.find_by_prefix_id(id) || scope.find_by(number: id)
+ rescue ArgumentError, NoMethodError
+ scope.find_by(number: id)
+ end
+
+ def import_kind(import)
+ import.class.name.demodulize.underscore
+ end
+
+ # Grouped so the assistant can say "12 rows failed because the SKU was
+ # missing" rather than reciting every row.
+ def failure_reasons(import)
+ failed = import.rows.failed.limit(200)
+ return if failed.empty?
+
+ failed.filter_map { |row| row.validation_errors.presence }
+ .tally
+ .sort_by { |_reason, count| -count }
+ .first(FAILED_ROW_SAMPLE)
+ .map { |reason, count| { reason: reason, rows: count } }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/get_resource.rb b/spree/core/app/tools/spree/agent_tools/get_resource.rb
new file mode 100644
index 0000000000..cd9d25ecb5
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/get_resource.rb
@@ -0,0 +1,79 @@
+module Spree
+ module AgentTools
+ # Fetches one record in full, for when the summary from a search is not
+ # enough to answer the question.
+ class GetResource < Spree::AgentTool
+ tool_name 'get_resource'
+ description 'Fetch one record in full by its id, e.g. prod_86Rf07xd4z or an order number.'
+ permission nil
+
+ param :resource, description: 'Resource key — call describe_resource for the list', required: true
+ param :id, description: 'The record id as shown in search results', required: true
+
+ def call(resource:, id:)
+ entry = Spree::AgentTools::ResourceMap.find(resource)
+ return { error: "Unknown resource #{resource.inspect}" } if entry.nil?
+ return { error: "You do not have permission to read #{entry.key}." } unless context.permitted?(entry.permission)
+
+ record = find_record(entry, id)
+ return { error: "No #{entry.key.singularize} found for #{id.inspect}" } if record.nil?
+
+ {
+ resource: entry.key,
+ # The full record for the model to answer from, plus the same
+ # compact row `search_resources` returns so the panel can show it
+ # as something the merchant can click through to.
+ #
+ # Sanitized like every other outbound record: this is the one tool
+ # that emits a whole serializer hash, so without the filter a
+ # serializer that gains a token field would send it straight to the
+ # AI vendor — the exact case the filter exists for.
+ record: Spree::AgentTools::RecordSummary.sanitize(entry.serializer_class.new(record).to_h),
+ records: [Spree::AgentTools::RecordSummary.call(entry: entry, record: record)],
+ count: 1,
+ total: 1
+ }
+ end
+
+ # Named, not identified: "Look up Rotary Shaver 9000" is what the
+ # merchant is watching happen. A prefixed id is our plumbing.
+ def summary(arguments)
+ entry = Spree::AgentTools::ResourceMap.find(arguments[:resource])
+ record = entry && find_record(entry, arguments[:id])
+ label = record && Spree::AgentTools::RecordSummary.call(entry: entry, record: record)[:title]
+
+ "Look up #{label.presence || arguments[:id]}"
+ rescue StandardError
+ "Look up #{arguments[:resource]}"
+ end
+
+ private
+
+ # Scoped through the store, so an id belonging to another store is a
+ # miss rather than a leak.
+ def find_record(entry, id)
+ scope = entry.scope_for(context)
+
+ scope.find_by_prefix_id(id) || find_by_natural_key(scope, id)
+ # Only the prefixed-id decode is expected to fail here (the model may
+ # pass a slug or an order number); anything else is a real error and
+ # must not be swallowed into a confusing nil.
+ rescue ArgumentError, NoMethodError
+ find_by_natural_key(scope, id)
+ end
+
+ # Merchants say order numbers and product slugs out loud far more often
+ # than prefixed ids, and the model repeats what the merchant said.
+ def find_by_natural_key(scope, id)
+ %i[number slug].each do |column|
+ next unless scope.klass.column_names.include?(column.to_s)
+
+ record = scope.find_by(column => id)
+ return record if record
+ end
+
+ nil
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb b/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb
new file mode 100644
index 0000000000..69fcae6aae
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb
@@ -0,0 +1,125 @@
+module Spree
+ module AgentTools
+ # Applies a column mapping to an import, and starts it if the mapping is
+ # complete.
+ #
+ # Mutating, and deliberately so. Mapping decides what every row in the
+ # file becomes: get "Cost" onto `price` instead of `cost_price` and a
+ # merchant has repriced their whole catalogue in one click. The merchant
+ # sees the proposed pairing and approves it before anything is written.
+ class ProposeImportMapping < Spree::AgentTool
+ tool_name 'propose_import_mapping'
+ description 'Map the columns of an uploaded import file onto Spree fields. ' \
+ 'Call describe_import_mapping first to see the real column headings ' \
+ 'and field names. Pass a mapping of spree_field => file_column; ' \
+ 'omit a field to leave it unmapped. The merchant approves before ' \
+ 'anything is applied.'
+ # The Admin API gates every import action on the write scope of the
+ # resource being imported — `write_products` for a product import —
+ # never on a settings key. Mirrored here, per-import, in `call`.
+ permission 'write_products'
+ mutating!
+
+ param :id, description: 'Import id or number', required: true
+ param :mapping, type: :object,
+ description: 'Spree field to file column, e.g. {"name": "Product Title"}',
+ required: true
+
+ def call(id:, mapping:)
+ import = find_import(id)
+ return { error: "No import found for #{id.inspect}" } if import.nil?
+
+ # Per-import, because a customer import needs `write_customers`
+ # while a product import needs `write_products`.
+ required = "write_#{import.class.required_scope}"
+ unless context.permitted?(required)
+ return { error: "You do not have permission to run a #{import_kind(import)} import." }
+ end
+
+ refusal = unauthorized(:update, import)
+ return refusal if refusal
+
+ return { error: 'This import is not waiting to be mapped.' } unless import.mapping?
+
+ pairs = sanitize(import, mapping)
+ return unknown_fields(import, mapping) if pairs.empty?
+
+ apply!(import, pairs)
+ start_if_ready(import)
+
+ {
+ ok: true,
+ id: import.prefixed_id,
+ mapped: pairs,
+ status: import.reload.status,
+ # `mapped_fields` returns mapping records, not names.
+ still_missing: import.required_fields - import.mappings.mapped.pluck(:schema_field)
+ }
+ end
+
+ # The merchant judges the pairing itself, so the card spells it out
+ # rather than saying "apply a mapping".
+ def summary(arguments)
+ pairs = (arguments[:mapping] || {}).map { |field, column| "#{column} → #{field}" }
+ return 'Apply an import mapping' if pairs.empty?
+
+ "Map #{pairs.join(', ')}"
+ end
+
+ private
+
+ def import_kind(import)
+ import.class.name.demodulize.underscore.tr('_', ' ')
+ end
+
+ def find_import(id)
+ scope = Spree::AgentTools::ResourceMap.find('imports').scope_for(context)
+
+ scope.find_by_prefix_id(id) || scope.find_by(number: id)
+ rescue ArgumentError, NoMethodError
+ scope.find_by(number: id)
+ end
+
+ # Only fields the schema declares and columns the file actually has —
+ # a hallucinated pairing must not reach the database.
+ def sanitize(import, mapping)
+ # `schema_fields` returns {name:, label:, required:} hashes, not names.
+ fields = import.schema_fields.map { |field| field[:name].to_s }
+ columns = import.csv_headers
+
+ (mapping || {}).to_h.filter_map do |field, column|
+ next unless fields.include?(field.to_s)
+ next unless column.blank? || columns.include?(column.to_s)
+
+ [field.to_s, column.presence&.to_s]
+ end.to_h
+ end
+
+ def apply!(import, pairs)
+ Spree::ImportMapping.transaction do
+ pairs.each do |field, column|
+ mapping = import.mappings.find_by(schema_field: field)
+ next if mapping.nil?
+
+ mapping.update!(file_column: column)
+ end
+ end
+ import.mappings.reload
+ end
+
+ # Starting the import is the same transition the dashboard's own
+ # mapping step makes, and only once every required field is satisfied.
+ def start_if_ready(import)
+ import.complete_mapping! if import.mapping_done?
+ end
+
+ def unknown_fields(import, mapping)
+ {
+ error: 'None of those fields or columns exist on this import.',
+ spree_fields: import.schema_fields.map { |field| field[:name] },
+ file_columns: import.csv_headers
+ }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/query_report.rb b/spree/core/app/tools/spree/agent_tools/query_report.rb
new file mode 100644
index 0000000000..89a49d74be
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/query_report.rb
@@ -0,0 +1,101 @@
+module Spree
+ module AgentTools
+ # Answers a reporting question — revenue by month, units by product,
+ # orders by channel — against the same semantic registry the dashboard
+ # charts read, so an agent and a chart cannot disagree about what a
+ # number means.
+ class QueryReport < Spree::AgentTool
+ tool_name 'query_report'
+ description 'Run a reporting query: pick metrics (revenue, orders, units) and dimensions ' \
+ '(time, product, channel, country) and get the aggregated rows. Call ' \
+ 'describe_reporting first for the metrics and dimensions this store has.'
+ permission 'read_reports'
+
+ param :metrics, type: :array, description: 'Metric names, e.g. ["revenue", "orders"]', required: true
+ param :dimensions, type: :array,
+ description: 'Dimensions to group by, e.g. ["time.month", "product"]. Omit for a single total.',
+ required: false
+ param :time_range, type: :object,
+ description: 'A preset such as {"preset": "last_30_days"}, or {"from": "2026-01-01", "to": "2026-03-31"}',
+ required: false
+ param :filters, type: :array, description: 'Dimension filters, e.g. [{"dimension": "channel", "values": ["web"]}]', required: false
+ param :sort, description: 'Metric or dimension to sort by, prefixed with - for descending', required: false
+ param :limit, type: :integer, description: 'Maximum rows to return (default 50)', required: false
+ param :currency, description: 'Currency for money metrics; defaults to the store currency', required: false
+
+ # Rows land in the model's context verbatim, so a query that would have
+ # returned thousands is capped rather than truncated silently.
+ DEFAULT_LIMIT = 50
+ MAX_LIMIT = 500
+
+ def call(metrics:, dimensions: nil, time_range: nil, filters: nil, sort: nil, limit: nil, currency: nil)
+ query = build_query(metrics: metrics, dimensions: dimensions, time_range: time_range,
+ filters: filters, sort: sort, limit: limit, currency: currency)
+
+ refusal = unauthorized_members(query)
+ return refusal if refusal
+
+ shape(query.execute)
+ rescue Spree::Reporting::UnknownMember => e
+ { error: e.message, valid: Array(e.valid).map(&:to_s) }
+ rescue Spree::Reporting::InvalidQuery => e
+ { error: e.message }
+ end
+
+ def summary(arguments)
+ metrics = Array(arguments[:metrics]).join(', ')
+ dimensions = Array(arguments[:dimensions])
+
+ dimensions.any? ? "Report #{metrics} by #{dimensions.join(', ')}" : "Report #{metrics}"
+ end
+
+ private
+
+ def build_query(metrics:, dimensions:, time_range:, filters:, sort:, limit:, currency:)
+ parameters = {
+ 'metrics' => Array(metrics),
+ 'dimensions' => Array(dimensions),
+ 'filters' => Array(filters),
+ 'limit' => [(limit || DEFAULT_LIMIT).to_i, MAX_LIMIT].min
+ }
+ parameters['time_range'] = time_range if time_range.present?
+ parameters['sort'] = sort if sort.present?
+ parameters['currency'] = currency if currency.present?
+
+ Spree::Reporting::Query.new(store: context.store, params: parameters)
+ end
+
+ # The same per-member check the reporting endpoint makes, in the same
+ # two flavours: a key is checked against its scopes, an admin against
+ # their ability. A caller who may read orders but not products cannot
+ # reach the product dimension here either.
+ def unauthorized_members(query)
+ if context.user_principal?
+ forbidden = query.unreadable_subjects(context.ability).first
+ return if forbidden.nil?
+
+ { error: "You do not have permission to report on #{forbidden.to_s.demodulize.underscore.humanize.downcase}." }
+ else
+ missing = query.required_key_scopes.reject { |scope| context.api_key.has_scope?(scope) }
+ return if missing.empty?
+
+ { error: "This API key lacks the #{missing.to_sentence} scope." }
+ end
+ end
+
+ # Totals first: most reporting questions are answered by them alone,
+ # and the rows are what fills a context window.
+ def shape(result)
+ rows = Array(result.rows)
+
+ {
+ totals: result.totals,
+ rows: rows,
+ row_count: rows.length,
+ meta: result.meta
+ }.compact
+ end
+
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/resource_write.rb b/spree/core/app/tools/spree/agent_tools/resource_write.rb
new file mode 100644
index 0000000000..49eb3ee51a
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/resource_write.rb
@@ -0,0 +1,101 @@
+module Spree
+ module AgentTools
+ # Shared behaviour for the generic record writes.
+ #
+ # These exist only for resources whose controller saves the record
+ # directly — store, market, channel, delivery, payment and tax setup. A
+ # resource written through a workflow refuses them and names its workflow
+ # tool instead, so there is exactly one way to write each thing and every
+ # write goes through the same validations, hooks and events the dashboard
+ # fires.
+ class ResourceWrite < Spree::AgentTool
+ mutating!
+
+ # Ungated at the class level because the gate is per resource: a key with
+ # `write_settings` may update a market but not a seller, and the resource
+ # is not known until the call. {#call} checks the entry's own write
+ # permission, and {#permitted?} offers the tool to anyone holding any
+ # write key at all.
+ permission nil
+
+ # Offered only to a caller who may write something, so a read-only key
+ # is never told these tools exist.
+ #
+ # @return [Boolean]
+ def permitted?
+ ResourceMap.all.any? { |entry| writable_for?(entry) }
+ end
+
+ protected
+
+ # Resolves the resource and refuses, in the model's own vocabulary, when
+ # it cannot be written generically.
+ #
+ # @param key [String]
+ # @return [Array(ResourceMap::Entry, nil), Array(nil, Hash)]
+ def writable_entry(key)
+ entry = ResourceMap.find(key)
+ return [nil, { error: "Unknown resource #{key.inspect}." }] if entry.nil?
+
+ unless entry.generic_writes?
+ return [nil, { error: refusal_for(entry) }]
+ end
+
+ unless context.permitted?(entry.write_permission)
+ return [nil, { error: "You do not have permission to change #{entry.key}." }]
+ end
+
+ [entry, nil]
+ end
+
+ # A resource with a workflow is not written here — the tool that does it
+ # is named, so the model retries correctly instead of giving up.
+ def refusal_for(entry)
+ workflow_key = entry.update_workflow_key || entry.create_workflow_key
+ return "#{entry.key} cannot be changed with this tool." if workflow_key.blank?
+
+ tool = workflow_key.tr('.', '_')
+ "#{entry.key} is written through a workflow — use the #{tool} tool instead."
+ end
+
+ # Only the attributes the Admin API itself would accept. Anything else is
+ # named back rather than silently dropped, so a model that guessed a
+ # field name learns the real one from `describe_resource`.
+ #
+ # @return [Array(Hash, nil), Array(nil, Hash)]
+ def permitted_attributes(entry, attributes)
+ attributes = (attributes || {}).transform_keys(&:to_s)
+ allowed = entry.writable_attribute_names
+ rejected = attributes.keys - allowed
+
+ if rejected.any?
+ return [nil, { error: "#{entry.key} does not accept #{rejected.to_sentence}. " \
+ "Accepted attributes: #{allowed.to_sentence}." }]
+ end
+
+ [attributes, nil]
+ end
+
+ # Saves through the model's own validations, and hands their messages
+ # back verbatim when it refuses.
+ def save_record(entry, record)
+ if record.save
+ { summary: summary_for(entry, record), record: RecordSummary.call(entry: entry, record: record) }
+ else
+ { error: record.errors.full_messages.to_sentence }
+ end
+ end
+
+ def summary_for(entry, record)
+ label = RecordSummary.call(entry: entry, record: record)[:title]
+ "#{self.class.tool_name.humanize} #{entry.key.singularize.humanize.downcase} #{label}"
+ end
+
+ private
+
+ def writable_for?(entry)
+ entry.generic_writes? && context.permitted?(entry.write_permission)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/search_resources.rb b/spree/core/app/tools/spree/agent_tools/search_resources.rb
new file mode 100644
index 0000000000..217e060af2
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/search_resources.rb
@@ -0,0 +1,146 @@
+module Spree
+ module AgentTools
+ # Searches store records.
+ #
+ # Every lookup starts from the current store's own association and is
+ # filtered through the model's Ransack allowlist, so the assistant can
+ # reach exactly what the Admin API would let this admin reach — no more.
+ class SearchResources < Spree::AgentTool
+ DEFAULT_LIMIT = 10
+ MAX_LIMIT = 25
+
+ tool_name 'search_resources'
+ description 'Search the store. Filters are Ransack predicates ' \
+ '(name_cont, created_at_gteq, status_eq) or named scopes passed as a ' \
+ 'bare key, e.g. {"out_of_stock": true} for stock questions or ' \
+ '{"price_lte": 20} for price. Call describe_resource to see every ' \
+ 'resource, field and scope available.'
+ # Per-resource permissions are enforced per call — this tool is offered
+ # whenever the admin can read anything at all.
+ permission nil
+
+ param :resource, description: 'Resource key — call describe_resource for the list', required: true
+ param :filters, type: :object, description: 'Ransack filter hash, e.g. {"name_cont": "shirt"}'
+ param :sort, description: 'Sort, e.g. "created_at desc"'
+ param :limit, type: :integer, description: "Max records to return (default #{DEFAULT_LIMIT})"
+
+ def call(resource:, filters: nil, sort: nil, limit: nil)
+ entry = Spree::AgentTools::ResourceMap.find(resource)
+ return unknown_resource(resource) if entry.nil?
+ return forbidden(entry) unless context.permitted?(entry.permission)
+
+ applied = sanitize_filters(filters)
+ # Ransack silently drops filters it does not recognise, so an invented
+ # field would quietly widen the search to everything and the assistant
+ # would report the result as a match. Reject it instead, and say which
+ # fields exist so the model can correct itself.
+ unrecognised = unrecognised_filters(entry, applied)
+ return invalid_filters(entry, unrecognised) if unrecognised.any?
+
+ query = build_query(entry, applied, sort)
+ # `accessible_by` builds LEFT JOINs for an association condition
+ # (`can :read, Product, categories: {...}`), so without `distinct` a
+ # record repeats once per matching row and the count is inflated —
+ # and the assistant states that count as fact.
+ result = query.result.distinct
+ records = result.limit(capped_limit(limit)).to_a
+
+ {
+ resource: entry.key,
+ # How many matched, not how many were returned. The assistant is
+ # asked to say how many there are, so handing it the page size would
+ # have it state "10 products" for a store holding hundreds.
+ total: result.count,
+ count: records.size,
+ records: records.map { |record| Spree::AgentTools::RecordSummary.call(entry: entry, record: record) }
+ }
+ end
+
+ def summary(arguments)
+ label = arguments[:resource].to_s.tr('_', ' ')
+ filters = arguments[:filters]
+ return "Search #{label}" if filters.blank?
+
+ # Name the filter in words, so the activity line says what is being
+ # looked for rather than only where.
+ described = filters.keys.map { |key| key.to_s.tr('_', ' ') }.join(', ')
+ "Search #{label} by #{described}"
+ end
+
+ private
+
+ def build_query(entry, filters, sort)
+ query = entry.scope_for(context).ransack(filters)
+ query.sorts = sort if sort.present?
+ query
+ end
+
+ # A filter key is either a named scope (`out_of_stock`) or an
+ # `<attribute>_<predicate>` pair. BOTH halves must be checked: Ransack
+ # runs with `ignore_unknown_conditions` on, so it silently drops a key
+ # it cannot parse and returns the whole collection — which the
+ # assistant then reports as the answer ("you have 38 products with
+ # status notreal"). Checking only the attribute prefix let exactly that
+ # through.
+ def unrecognised_filters(entry, filters)
+ scopes = entry.filterable_scopes
+
+ filters.keys.reject do |key|
+ name = key.to_s
+ scopes.include?(name) || valid_attribute_predicate?(entry, name)
+ end
+ end
+
+ # Longest attribute first, so a field whose name is a prefix of another
+ # (`name` vs `name_of_thing`) does not shadow it.
+ def valid_attribute_predicate?(entry, key)
+ entry.filterable_fields.sort_by { |field| -field.length }.any? do |field|
+ next false unless key.start_with?(field)
+ # A bare attribute means Ransack's default `eq`.
+ next true if key == field
+
+ predicate = key.delete_prefix("#{field}_")
+ ransack_predicates.include?(predicate)
+ end
+ end
+
+ # Every predicate Ransack knows, including the compound `_any`/`_all`
+ # suffixes it generates.
+ def ransack_predicates
+ @ransack_predicates ||= Ransack.predicates.keys.to_set
+ end
+
+ def invalid_filters(entry, keys)
+ {
+ error: "Unknown filter(s): #{keys.join(', ')}",
+ filterable_fields: entry.filterable_fields,
+ filterable_scopes: entry.filterable_scopes
+ }
+ end
+
+ # Empty values match everything, so they are dropped — but `false` is a
+ # real filter value (`{"out_of_stock": false}`), and `compact_blank`
+ # would have thrown it away and quietly returned the whole collection.
+ def sanitize_filters(filters)
+ (filters || {}).to_h.reject { |_key, value| value.nil? || value == '' }
+ end
+
+ def capped_limit(limit)
+ return DEFAULT_LIMIT if limit.blank?
+
+ [[limit.to_i, 1].max, MAX_LIMIT].min
+ end
+
+ def unknown_resource(resource)
+ {
+ error: "Unknown resource #{resource.inspect}",
+ available: Spree::AgentTools::ResourceMap.available_for(context).map(&:key)
+ }
+ end
+
+ def forbidden(entry)
+ { error: "You do not have permission to read #{entry.key}." }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/update_resource.rb b/spree/core/app/tools/spree/agent_tools/update_resource.rb
new file mode 100644
index 0000000000..e8b4724092
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/update_resource.rb
@@ -0,0 +1,30 @@
+module Spree
+ module AgentTools
+ # Changes a record of a resource the Admin API writes directly.
+ class UpdateResource < Spree::AgentTools::ResourceWrite
+ tool_name 'update_resource'
+ description 'Change a store setup record — a market, channel, delivery method, payment ' \
+ 'method, tax rate and so on. Call describe_resource first for the attributes ' \
+ 'a resource accepts. Catalog and order records are changed by their own tools.'
+
+ param :resource, description: 'Resource key — call describe_resource for the list', required: true
+ param :id, description: 'The record id as shown in search results', required: true
+ param :attributes, type: :object, description: 'Attributes to change', required: true
+
+ def call(resource:, id:, attributes: {})
+ entry, refusal = writable_entry(resource)
+ return refusal if refusal
+
+ record = entry.scope_for(context, :update).find_by_prefix_id(id)
+ return { error: "No #{entry.key.singularize} found for #{id.inspect}." } if record.nil?
+ return { error: "You do not have permission to change this #{entry.key.singularize}." } unless context.can?(:update, record)
+
+ permitted, rejection = permitted_attributes(entry, attributes)
+ return rejection if rejection
+
+ record.assign_attributes(permitted)
+ save_record(entry, record)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/purchase_orders/create.rb b/spree/core/app/workflows/spree/purchase_orders/create.rb
index 9e86139cd9..c83fba970c 100644
--- a/spree/core/app/workflows/spree/purchase_orders/create.rb
+++ b/spree/core/app/workflows/spree/purchase_orders/create.rb
@@ -17,6 +17,9 @@ module Spree
# @param currency [String, nil] defaults to the store's; set it for a
# foreign-currency order
# @param expected_at [Date, nil]
+ # @param cancel_by [Date, nil] the date past which the merchant no longer
+ # wants the goods, so an order still open after it reads as overdue to
+ # cancel rather than merely late
# @param reference [String, nil] the supplier's own order number
# @param notes [String, nil]
# @param metadata [Hash, nil]
diff --git a/spree/core/lib/spree/agent_tool.rb b/spree/core/lib/spree/agent_tool.rb
new file mode 100644
index 0000000000..fed5fe16f7
--- /dev/null
+++ b/spree/core/lib/spree/agent_tool.rb
@@ -0,0 +1,152 @@
+module Spree
+ # One entry in the agent-tool registry ({Spree.agent_tools}).
+ #
+ # A tool is a plain Spree object: a name, a description the model reads, a
+ # JSON parameter schema, the permission key that gates it, whether it
+ # mutates the store, and an executor. Nothing here knows which client is
+ # asking — the MCP server and the dashboard assistant are both adapters
+ # over this one registry, so a tool registered once is offered by both.
+ #
+ # Subclasses implement {#call} and declare their metadata with the class-level
+ # DSL:
+ #
+ # class Spree::AgentTools::SearchResources < Spree::AgentTool
+ # tool_name 'search_resources'
+ # description 'Search store records.'
+ # permission 'read_products'
+ # param :resource, description: 'What to search', required: true
+ #
+ # def call(resource:)
+ # # ...
+ # end
+ # end
+class AgentTool
+ # Declarations live in class attributes rather than plain class-level
+ # instance variables so a subclass inherits them. Subclassing a tool to
+ # tweak it is the documented extension path, and with bare ivars the
+ # subclass would come back `mutating? == false` — writing to the store
+ # immediately, with no approval card, no permission gate and no argument
+ # validation. Inheritance here is a safety property, not a convenience.
+ class_attribute :declared_tool_name, instance_accessor: false
+ class_attribute :declared_description, instance_accessor: false
+ class_attribute :declared_permission, instance_accessor: false
+ class_attribute :declared_mutating, instance_accessor: false, default: false
+ class_attribute :declared_params, instance_accessor: false, default: {}.freeze
+
+ class << self
+ # @return [String] the name the model calls this tool by
+ def tool_name(value = nil)
+ self.declared_tool_name = value if value
+ declared_tool_name
+ end
+
+ # @return [String] what the tool does, read by the model when choosing
+ def description(value = nil)
+ self.declared_description = value if value
+ declared_description
+ end
+
+ # RBAC permission key required to use this tool. A user without it never
+ # sees the tool in the list handed to the model.
+ #
+ # @return [String]
+ def permission(value = nil)
+ self.declared_permission = value if value
+ declared_permission
+ end
+
+ # Declares that this tool changes store data, so the turn halts for
+ # human approval instead of executing.
+ #
+ # @return [void]
+ def mutating!
+ self.declared_mutating = true
+ end
+
+ # @return [Boolean]
+ def mutating?
+ declared_mutating == true
+ end
+
+ # @param name [Symbol]
+ # @param type [Symbol] JSON schema type
+ # @param description [String]
+ # @param required [Boolean]
+ # @return [void]
+ def param(name, type: :string, description: nil, required: false)
+ # Reassigned rather than mutated, so declaring a param on a subclass
+ # does not reach back and change the parent's list.
+ self.declared_params = declared_params.merge(
+ name => { type: type, description: description, required: required }
+ ).freeze
+ end
+
+ # @return [Hash{Symbol => Hash}]
+ def params
+ declared_params
+ end
+ end
+
+ # @return [Spree::AgentTools::Context] who is asking, and where
+ attr_reader :context
+
+ # @param context [Spree::AgentTools::Context]
+ def initialize(context)
+ @context = context
+ end
+
+ delegate :tool_name, :description, :permission, :mutating?, :params, to: :class
+
+ # Runs the tool. Subclasses implement this with keyword arguments matching
+ # their declared params.
+ #
+ # @return [Hash] the result handed back to the model
+ def call(**)
+ raise NotImplementedError, 'Agent tools must implement #call'
+ end
+
+ # One line saying what approving this call would do. It is the entire
+ # approval card — the merchant decides on this sentence and nothing else,
+ # so every mutating tool should override it with something that reads
+ # like an instruction ("Set Blue Shirt to draft"), naming the record
+ # rather than its id.
+ #
+ # The fallback spells the arguments out rather than dumping JSON, so a
+ # tool that forgets to override is merely terse instead of unreadable.
+ #
+ # @param arguments [Hash]
+ # @return [String]
+ def summary(arguments)
+ described = arguments.map { |key, value| "#{key.to_s.humanize.downcase} #{value}" }.join(', ')
+
+ [tool_name.humanize, described.presence].compact.join(': ')
+ end
+
+ # Whether the asking user may use this tool at all.
+ #
+ # @return [Boolean]
+ def permitted?
+ context.permitted?(permission)
+ end
+
+ protected
+
+ # Refuses unless this admin may take `action` on `record`.
+ #
+ # Holding `write_products` says an admin may edit products; it does not
+ # say they may edit *this* one. A host app can narrow that with a
+ # record-level rule, and the Admin API honours it — so any tool that
+ # changes a record must ask here first. Returns an error the model reads
+ # rather than raising, so the assistant explains itself instead of the
+ # turn dying.
+ #
+ # @param action [Symbol]
+ # @param record [Object]
+ # @return [Hash, nil] an error result to return, or nil when allowed
+ def unauthorized(action, record)
+ return if context.can?(action, record)
+
+ { error: "You do not have permission to #{action} this #{record.class.name.demodulize.underscore.humanize.downcase}." }
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools.rb b/spree/core/lib/spree/agent_tools.rb
new file mode 100644
index 0000000000..deda5031f9
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools.rb
@@ -0,0 +1,21 @@
+require 'spree/agent_tools/registry'
+require 'spree/agent_tools/context'
+require 'spree/agent_tools/resource_map'
+require 'spree/agent_tools/record_summary'
+require 'spree/agent_tools/workflow_schema'
+require 'spree/agent_tools/workflow_tool'
+require 'spree/agent_tools/default_catalog'
+
+module Spree
+ # The agent-tool contract: what an MCP client or the dashboard assistant may
+ # do on a merchant's behalf, and under whose authority.
+ #
+ # Nothing here talks to a model or a protocol. A tool is a name, a
+ # description, a JSON parameter schema, a permission key, a mutating flag
+ # and an executor — see {Spree::AgentTool} — and the adapters in `spree_mcp`
+ # and the dashboard assistant turn that into their own vocabulary.
+ #
+ # See docs/plans/6.0-mcp-server.md.
+ module AgentTools
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools/context.rb b/spree/core/lib/spree/agent_tools/context.rb
new file mode 100644
index 0000000000..c5da4fc52f
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/context.rb
@@ -0,0 +1,134 @@
+module Spree
+ module AgentTools
+ # Who is asking, and where. Every tool executes inside one of these, so a
+ # tool can never reach data the caller could not reach through the Admin
+ # API: lookups scope through {#store}, and {#permitted?} decides which
+ # tools the model is even offered.
+ #
+ # Two kinds of caller, because the registry serves two adapters. The
+ # dashboard assistant asks on behalf of a signed-in admin, so its context
+ # carries a user and that user's ability. The MCP server asks on behalf of
+ # a secret API key, so its context carries the key and the key's scopes.
+ # Whichever it is, {#principal} is the thing that acted — which is what a
+ # workflow records as the canceller or approver.
+ #
+ # Context.new(store: store, user: admin)
+ # Context.new(store: store, api_key: key)
+ class Context
+ # @return [Spree::Store]
+ attr_reader :store
+
+ # @return [Object, nil] the signed-in admin ({Spree.admin_user_class}),
+ # or nil when a key is asking
+ attr_reader :user
+
+ # @return [Spree::ApiKey, nil] the authenticating secret key, or nil when
+ # an admin is asking
+ attr_reader :api_key
+
+ # @return [Spree::Ability, nil] the user's ability; nil for a key, whose
+ # authority is its scopes
+ attr_reader :ability
+
+ # @param store [Spree::Store]
+ # @param user [Object, nil] a {Spree.admin_user_class} record
+ # @param api_key [Spree::ApiKey, nil] a secret key
+ # @param ability [Spree::Ability, nil] defaults to the user's ability for
+ # this store — abilities are store-scoped, so the store must be passed
+ def initialize(store:, user: nil, api_key: nil, ability: nil)
+ raise ArgumentError, 'Spree::AgentTools::Context needs a user or an api_key' if user.nil? && api_key.nil?
+
+ @store = store
+ @user = user
+ @api_key = api_key
+ @ability = ability || (Spree::Dependencies.ability_class.constantize.new(user, store: store) if user)
+ end
+
+ # Who acted, for workflows that record it (`canceler:`, `approver:`,
+ # `created_by:`). An admin user or an API key — both are registered in
+ # `Spree.actor_classes`, so either can be stored polymorphically.
+ #
+ # @return [Object]
+ def principal
+ user || api_key
+ end
+ alias actor principal
+
+ # @return [Boolean] whether a signed-in admin is asking
+ def user_principal?
+ user.present?
+ end
+
+ # Narrows a relation to the records this caller may act on, the same way
+ # an Admin API controller does.
+ #
+ # For an admin, permission keys answer "may they touch products at all";
+ # they do not answer "which products". A host app that registers a
+ # record-level rule (`can :read, Spree::Order, seller_id: ...`) is
+ # honoured by the Admin API, and must be honoured here too.
+ #
+ # For a key there is no record-level filter to apply: a secret key's
+ # authority is its scopes, and the store is the whole tenancy answer —
+ # exactly how the Admin API treats key requests today.
+ #
+ # @param relation [ActiveRecord::Relation]
+ # @param action [Symbol]
+ # @return [ActiveRecord::Relation]
+ def accessible(relation, action = :show)
+ return relation unless user_principal?
+ return relation unless relation.respond_to?(:accessible_by)
+
+ relation.accessible_by(ability, action)
+ end
+
+ # Whether this caller may take an action on a specific record.
+ #
+ # Checked at execution rather than at proposal time: an approval card may
+ # be decided minutes later, and roles can change in between. A key holds
+ # no record-level rules, so its scope check is the whole answer.
+ #
+ # @param record [Object]
+ # @param action [Symbol]
+ # @return [Boolean]
+ def can?(action, record)
+ return true unless user_principal?
+
+ ability.can?(action, record)
+ end
+
+ # @param permission_key [String, nil]
+ # @return [Boolean] whether the caller holds this permission
+ def permitted?(permission_key)
+ return true if permission_key.blank?
+
+ key = permission_key.to_s
+ # An unregistered key can never be held, so a typo would silently hide a
+ # tool forever. Fail loudly in development instead.
+ if !Spree.permissions.key?(key) && (defined?(Rails) && Rails.env.local?)
+ raise ArgumentError, "Agent tool declares unknown permission key #{key.inspect}"
+ end
+
+ permission_keys.include?(key)
+ end
+
+ # The catalog keys this caller holds, in the one currency both gates
+ # speak: an admin's activated role keys, or a secret key's scopes
+ # expanded the way the Admin API expands them (`write_x` implies
+ # `read_x`, `read_all` and `write_all` fan out over the catalog).
+ #
+ # The `respond_to?` guard on the ability is house style:
+ # `Spree::Dependencies.ability_class` is swappable and a custom class
+ # need not implement it.
+ #
+ # @return [Array<String>]
+ def permission_keys
+ @permission_keys ||=
+ if user_principal?
+ ability.respond_to?(:permission_keys) ? Array(ability.permission_keys).map(&:to_s) : []
+ else
+ Spree.permissions.expand_keys(api_key.scopes)
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools/default_catalog.rb b/spree/core/lib/spree/agent_tools/default_catalog.rb
new file mode 100644
index 0000000000..b8432d5dc3
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb
@@ -0,0 +1,137 @@
+module Spree
+ module AgentTools
+ # The tools Spree ships: the generic read tools, and the workflows exposed
+ # as write tools.
+ #
+ # The write allowlist is the whole catalog of back-office writes an agent
+ # may make. Every entry names a `Spree::Dependencies` key, so a host app
+ # that swaps in its own workflow class keeps the tool and gets the
+ # replacement's schema; and a permission, which must equal the write scope
+ # of the admin controller that invokes the same workflow — a contract spec
+ # in `spree_api` fails when the two disagree, or when a controller gains a
+ # workflow that is neither listed here nor excluded below.
+ module DefaultCatalog
+ # Read tools, and the writes that are not workflows.
+ TOOLS = %w[
+ Spree::AgentTools::SearchResources
+ Spree::AgentTools::GetResource
+ Spree::AgentTools::DescribeResource
+ Spree::AgentTools::CreateResource
+ Spree::AgentTools::UpdateResource
+ Spree::AgentTools::DeleteResource
+ Spree::AgentTools::QueryReport
+ Spree::AgentTools::DescribeReporting
+ Spree::AgentTools::CreateExport
+ Spree::AgentTools::GetImportStatus
+ Spree::AgentTools::DescribeImportMapping
+ Spree::AgentTools::ProposeImportMapping
+ ].freeze
+
+ # Workflow key => permission, or => {permission:, except:, summary:}.
+ WORKFLOWS = {
+ # Catalog
+ product_create_workflow: 'write_products',
+ product_update_workflow: 'write_products',
+ product_destroy_workflow: 'write_products',
+ product_activate_workflow: 'write_products',
+ product_draft_workflow: 'write_products',
+ product_archive_workflow: 'write_products',
+ product_approve_workflow: 'write_products',
+ product_reject_workflow: 'write_products',
+ variant_create_workflow: 'write_products',
+ variant_update_workflow: 'write_products',
+ catalog_create_workflow: 'write_products',
+ catalog_update_workflow: 'write_products',
+ catalog_activate_workflow: 'write_products',
+ catalog_deactivate_workflow: 'write_products',
+ price_list_create_workflow: 'write_products',
+ price_list_update_workflow: 'write_products',
+ price_list_activate_workflow: 'write_products',
+ price_list_deactivate_workflow: 'write_products',
+
+ # 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] },
+
+ # Fulfillment
+ fulfillment_create_workflow: 'write_fulfillments',
+ fulfillment_mark_delivered_workflow: 'write_fulfillments',
+ delivery_update_tracking_workflow: 'write_orders',
+ shipping_label_purchase_workflow: 'write_orders',
+ shipping_label_refund_workflow: 'write_orders',
+
+ # Money
+ payment_capture_workflow: 'write_payments',
+ payment_void_workflow: 'write_payments',
+ refund_create_workflow: 'write_refunds',
+
+ # Inventory
+ stock_transfer_create_workflow: 'write_stock',
+ stock_transfer_update_workflow: 'write_stock',
+ stock_transfer_mark_ready_workflow: 'write_stock',
+ stock_transfer_mark_in_transit_workflow: 'write_stock',
+ stock_transfer_receive_workflow: 'write_stock',
+ stock_transfer_cancel_workflow: 'write_stock',
+ stock_transfer_mark_draft_workflow: 'write_stock',
+ stock_transfer_close_workflow: 'write_stock',
+
+ # Purchasing
+ purchase_order_create_workflow: 'write_purchasing',
+ purchase_order_update_workflow: 'write_purchasing',
+ purchase_order_mark_ordered_workflow: 'write_purchasing',
+ purchase_order_receive_workflow: 'write_purchasing',
+ purchase_order_cancel_workflow: 'write_purchasing',
+ purchase_order_mark_draft_workflow: 'write_purchasing',
+ purchase_order_close_workflow: 'write_purchasing',
+
+ # Marketplace
+ seller_create_workflow: 'write_sellers',
+ seller_invite_workflow: 'write_sellers',
+ seller_approve_workflow: 'write_sellers',
+ seller_reject_workflow: 'write_sellers',
+ seller_suspend_workflow: 'write_sellers',
+ seller_reopen_onboarding_workflow: 'write_sellers',
+ seller_requirement_submission_accept_workflow: 'write_sellers',
+ seller_requirement_submission_reject_workflow: 'write_sellers',
+ seller_requirement_submission_waive_workflow: 'write_sellers',
+
+ # B2B
+ tax_exemption_certificate_verify_workflow: 'write_customers'
+ }.freeze
+
+ # Workflows an admin controller invokes that are deliberately NOT tools,
+ # each with the reason. The contract spec reads this list, so a workflow
+ # can never be quietly dropped: it is exposed, or it is here.
+ EXCLUDED_WORKFLOWS = {
+ customer_anonymize_workflow:
+ 'Irreversible erasure of a person\'s data under GDPR Art. 17. A deletion no one can undo ' \
+ 'is not something to offer a model behind one confirmation prompt.',
+ invitation_accept_workflow:
+ 'Platform plumbing, not a merchant operation: it runs for the invited person from a ' \
+ 'tokenised link, and the controller skips the scope check entirely.',
+ seller_payout_sweep_workflow:
+ 'Moves money to every eligible seller at once. A scheduled platform job, not a ' \
+ 'conversational action.',
+ seller_payout_complete_workflow:
+ 'Settles a payout against the payment provider. Belongs to the payouts pipeline, which ' \
+ 'reconciles against provider state the agent cannot see.',
+ import_start_mapping_workflow:
+ 'Step of the CSV import wizard, driven by a file upload. MCP carries no files.',
+ import_complete_mapping_workflow:
+ 'Step of the CSV import wizard; the mapping proposal that feeds it stays in the ' \
+ 'dashboard assistant, which has the model.',
+ import_retry_failed_rows_workflow:
+ 'Step of the CSV import wizard, meaningful only against a run the agent did not start.'
+ }.freeze
+
+ class << self
+ # @param registry [Spree::AgentTools::Registry]
+ # @return [void]
+ def install(registry)
+ TOOLS.each { |tool| registry << tool }
+ registry.expose_workflows(**WORKFLOWS)
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools/record_summary.rb b/spree/core/lib/spree/agent_tools/record_summary.rb
new file mode 100644
index 0000000000..6287c185b7
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/record_summary.rb
@@ -0,0 +1,112 @@
+module Spree
+ module AgentTools
+ # Turns a record into the compact shape both the model and the panel read.
+ #
+ # One shape serves both audiences deliberately: the model needs enough to
+ # answer the question, and the panel needs enough to render a row the
+ # merchant can click through to. Anything richer belongs in `get_resource`.
+ class RecordSummary
+ # Fields worth showing beneath the title, in the order they are preferred.
+ # Status is deliberately absent — it has its own badge on the row, and
+ # repeating it would push out the field that actually adds something.
+ SUBTITLE_FIELDS = %w[display_total display_price price email number sku].freeze
+
+ # Anything that looks like a credential is dropped before a record can
+ # reach the model. The serializers are supposed to mask these already —
+ # this is the second lock, because a serializer that gains a field later
+ # would otherwise send live secrets to an AI vendor with no code change
+ # here at all.
+ SECRET_PATTERN = /(token|secret|password|api_key|access_key|private)/i.freeze
+
+ # Whole associations that are never safe to forward, whatever their
+ # serializer happens to expose today. A gift card's code IS the bearer
+ # instrument — anyone holding it can spend the balance — and an order
+ # serializes its gift card unconditionally, so an order lookup would
+ # otherwise hand live codes to the AI vendor and write them into chat
+ # history. A plain `code` match is too broad: channels, promotions and
+ # commission rates all use `code` as an identifier merchants ask about.
+ SECRET_ASSOCIATIONS = %w[gift_card gift_cards].freeze
+
+ class << self
+ # Strips credential-shaped keys from a serialized record.
+ #
+ # Public because it is the ONE filter every outbound record must pass:
+ # `get_resource` emits a full serializer hash rather than a summary row,
+ # and without this it would bypass the protection entirely.
+ #
+ # Recursive, because serializers nest: an order carries a gift card, a
+ # customer carries addresses. A shallow reject would scrub the top level
+ # and hand the vendor whatever sat one layer down, which is the failure
+ # this filter exists to prevent.
+ #
+ # @param attributes [Hash]
+ # @return [Hash]
+ def sanitize(value)
+ case value
+ when Hash
+ value.to_h.stringify_keys.each_with_object({}) do |(key, nested), result|
+ next if key.match?(SECRET_PATTERN) || SECRET_ASSOCIATIONS.include?(key)
+
+ result[key] = sanitize(nested)
+ end
+ when Array
+ value.map { |element| sanitize(element) }
+ else
+ value
+ end
+ end
+
+ # @param entry [Spree::AgentTools::ResourceMap::Entry]
+ # @param record [ActiveRecord::Base]
+ # @return [Hash]
+ def call(entry:, record:)
+ attributes = serialize(entry, record)
+ title = title_for(record, attributes)
+
+ {
+ id: record.prefixed_id,
+ resource: entry.key,
+ title: title,
+ subtitle: subtitle_for(attributes, title),
+ status: attributes['status'],
+ image_url: attributes['thumbnail_url'],
+ # The dashboard route this record lives at, so the panel links
+ # straight to it instead of the merchant hunting for it.
+ path: entry.dashboard_path_for(record)
+ }.compact
+ end
+
+ private
+
+ def serialize(entry, record)
+ sanitize(entry.serializer_class.new(record).to_h)
+ rescue StandardError => e
+ Rails.logger.warn("[Spree] #{entry.key} serializer failed: #{e.class}: #{e.message}")
+ {}
+ end
+
+ def title_for(record, attributes)
+ attributes['name'].presence ||
+ attributes['number'].presence ||
+ attributes['email'].presence ||
+ record.try(:name).presence ||
+ record.try(:number).presence ||
+ record.to_s
+ end
+
+ def subtitle_for(attributes, title)
+ value = SUBTITLE_FIELDS.filter_map { |field| formatted(attributes[field]) }.first
+ # A subtitle that repeats the title (a customer whose name IS their
+ # email) is a wasted line.
+ value unless value == title
+ end
+
+ def formatted(value)
+ return if value.blank?
+
+ value.to_s
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools/registry.rb b/spree/core/lib/spree/agent_tools/registry.rb
new file mode 100644
index 0000000000..7881e1a2b8
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/registry.rb
@@ -0,0 +1,122 @@
+module Spree
+ module AgentTools
+ # The agent-tool registry, reached as {Spree.agent_tools}. Extensions append
+ # their own tool classes the same way they register tax or delivery-rate
+ # providers:
+ #
+ # Spree.agent_tools << MyApp::AgentTools::SyncSupplier
+ #
+ # Registration is by class, so one registry serves every adapter: the MCP
+ # server and the dashboard assistant both read it.
+ #
+ # Writes are not registered as classes. A back-office write already is a
+ # workflow, so the registry exposes workflows by their `Spree::Dependencies`
+ # key and derives each tool from the workflow's own `perform` signature —
+ # see {#expose_workflows}.
+ class Registry
+ include Enumerable
+
+ def initialize(tool_names = [])
+ @tool_names = tool_names.map(&:to_s)
+ @exposed_workflows = {}
+ end
+
+ # Registered by name, resolved on use.
+ #
+ # Holding the class itself would pin the copy loaded at boot, so in
+ # development every edit to a tool's description, params or permission
+ # needed a restart to take effect — and tuning those descriptions is how
+ # an agent's behaviour is shaped. Names survive reloading, which is the
+ # same reason `Spree.integrations` stores strings.
+ #
+ # @param tool_class [Class<Spree::AgentTool>, String]
+ # @return [self]
+ def <<(tool_class)
+ name = tool_class.to_s
+ @tool_names << name unless @tool_names.include?(name)
+ self
+ end
+ alias add <<
+
+ def each(&)
+ to_a.each(&)
+ end
+
+ # Exposes workflows as write tools, keyed by `Spree::Dependencies` key so
+ # the tool follows whatever class the host app has registered:
+ #
+ # Spree.agent_tools.expose_workflows(
+ # order_cancel_workflow: 'write_orders',
+ # product_activate_workflow: 'write_products'
+ # )
+ #
+ # A value may be the permission key on its own, or a hash carrying it
+ # alongside `except:` (parameters to hide, such as a deprecated one) and
+ # `summary:` (a callable overriding the generated confirmation line).
+ #
+ # @param exposures [Hash{Symbol => String, Hash}]
+ # @return [self]
+ def expose_workflows(**exposures)
+ exposures.each do |dependency_key, options|
+ options = { permission: options } if options.is_a?(String) || options.is_a?(Symbol)
+ @exposed_workflows[dependency_key.to_sym] = {
+ permission: options.fetch(:permission).to_s,
+ except: Array(options[:except]).map(&:to_sym),
+ summary: options[:summary]
+ }
+ end
+ self
+ end
+
+ # @return [Hash{Symbol => Hash}] every exposed workflow, by dependency key
+ attr_reader :exposed_workflows
+
+ # Forgets every workflow exposure. For specs that register their own.
+ #
+ # @return [void]
+ def reset_workflows!
+ @exposed_workflows = {}
+ end
+
+ # @return [Array<Class<Spree::AgentTool>>]
+ def to_a
+ registered_classes + workflow_tool_classes
+ end
+
+ # @param name [String]
+ # @return [Class<Spree::AgentTool>, nil]
+ def find_by_name(name)
+ to_a.find { |tool_class| tool_class.tool_name == name.to_s }
+ end
+
+ # Tools this caller may actually use, instantiated for their context.
+ # This is what an adapter offers the model — a caller without
+ # `write_products` never learns that a price-changing tool exists.
+ #
+ # @param context [Spree::AgentTools::Context]
+ # @return [Array<Spree::AgentTool>]
+ def available_for(context)
+ to_a.map { |tool_class| tool_class.new(context) }.select(&:permitted?)
+ end
+
+ private
+
+ def registered_classes
+ @tool_names.filter_map do |name|
+ name.safe_constantize.tap do |klass|
+ Rails.logger.warn("[Spree] registered agent tool #{name} does not exist") if klass.nil?
+ end
+ end
+ end
+
+ # One generated tool class per exposed workflow whose dependency key
+ # still resolves. A key an extension removed simply stops being offered
+ # rather than breaking the whole catalog.
+ def workflow_tool_classes
+ @exposed_workflows.filter_map do |dependency_key, options|
+ Spree::AgentTools::WorkflowTool.for(dependency_key, **options)
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools/resource_map.rb b/spree/core/lib/spree/agent_tools/resource_map.rb
new file mode 100644
index 0000000000..0cdf6f719f
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/resource_map.rb
@@ -0,0 +1,195 @@
+module Spree
+ module AgentTools
+ # What the generic tools are allowed to look at.
+ #
+ # Not a hand-written list: the Admin API's controllers already declare
+ # their model, serializer and permission scope, so the map is derived from
+ # them — `spree_api` registers one entry per admin resource controller
+ # after the classes load. Core owns the structure and the refusal below;
+ # a resource no controller serves is not reachable by any agent.
+ #
+ # Permissions therefore mirror the controllers by construction rather than
+ # by convention: the catalog has no `read_price_lists`, and the price-lists
+ # controller rides `read_products`, so the derived entry does too.
+ class ResourceMap
+ # A registered resource whose model has no store scoping. Raised rather
+ # than quietly leaking another store's records.
+ UnscopedResourceError = Class.new(StandardError)
+
+ Entry = Struct.new(:key, :model_name, :permission, :serializer_name,
+ :dashboard_path, :scope_name, :write_permission,
+ :writable_attributes, :create_workflow_key, :update_workflow_key,
+ keyword_init: true) do
+ # Whether the generic write tools may touch this resource at all.
+ # A resource written through a workflow must be written through its
+ # workflow tool, so there is exactly one way to write each thing.
+ #
+ # @return [Boolean]
+ def generic_writes?
+ create_workflow_key.blank? && update_workflow_key.blank? && write_permission.present?
+ end
+
+ # The attributes the Admin API would accept on a write, so the generic
+ # tools offer exactly the same surface as the endpoint.
+ #
+ # @return [Array<String>]
+ def writable_attribute_names
+ Array(writable_attributes).map(&:to_s).sort
+ end
+ # Where this record lives in the dashboard, so an answer links to it
+ # rather than describing where to look. Store-relative — the panel
+ # prefixes the current store segment.
+ #
+ # @param record [ActiveRecord::Base]
+ # @return [String, nil]
+ def dashboard_path_for(record)
+ return if dashboard_path.blank?
+
+ format(dashboard_path, id: record.prefixed_id)
+ end
+
+ # @return [Class]
+ def model_class
+ model_name.constantize
+ end
+
+ # Records of this kind the asking admin may see.
+ #
+ # Takes the context rather than the store so the ability filter cannot
+ # be skipped by forgetting to apply it: store scoping answers tenancy,
+ # `accessible` answers which records within that tenant — the same two
+ # steps an Admin API controller takes.
+ #
+ # @param context [Spree::AgentTools::Context]
+ # @param action [Symbol]
+ # @return [ActiveRecord::Relation]
+ def scope_for(context, action = :show)
+ relation = model_class.for_store(context.store)
+
+ # `Spree::Base.for_store` falls back to the bare class when a model
+ # has no matching Store association, returning EVERY store's rows.
+ # A model that defines its own `for_store` has made a deliberate
+ # choice (customers are global by design, and Spree::Customer says
+ # so); inheriting the fallback is an accident. Only the accident is
+ # refused, because serving another store's records to an assistant
+ # that reads them aloud is worse than a missing resource.
+ if model_class.method(:for_store).owner == Spree::Base.singleton_class && relation.equal?(model_class)
+ raise UnscopedResourceError, key
+ end
+
+ # A resource that is a slice of a model rather than the whole of it
+ # (draft orders among orders) narrows further.
+ relation = relation.public_send(scope_name) if scope_name.present?
+
+ context.accessible(relation, action)
+ end
+
+ # Whether this resource's scoping is deliberate — either a real
+ # store relation, or a model that owns its `for_store` and has decided
+ # it is global.
+ #
+ # @return [Boolean]
+ def store_scoped?
+ model_class.method(:for_store).owner != Spree::Base.singleton_class ||
+ !model_class.for_store(Spree::Store.new).equal?(model_class)
+ rescue StandardError
+ false
+ end
+
+ # @return [Class] the admin serializer for this resource
+ def serializer_class
+ serializer_name.constantize
+ end
+
+ # Fields the model actually allows filtering and sorting on. Reused from
+ # the model's own Ransack allowlist so the assistant can never query a
+ # field the API would refuse.
+ #
+ # @return [Array<String>]
+ def filterable_fields
+ model_class.ransackable_attributes.sort
+ end
+
+ # Named queries the model exposes — `in_stock`, `out_of_stock`,
+ # `price_lte` and so on. These answer the questions merchants actually
+ # ask ("what's out of stock?") and cannot be expressed as an attribute
+ # filter, because the answer lives across stock levels rather than in a
+ # column. Passed as bare keys rather than `field_predicate` pairs.
+ #
+ # @return [Array<String>]
+ def filterable_scopes
+ model_class.ransackable_scopes.map(&:to_s).sort
+ end
+ end
+
+
+ class << self
+ # @return [Array<Entry>] every registered resource, in registration order
+ def all
+ entries.values
+ end
+
+ # Registers one resource. Called by `spree_api` for each admin resource
+ # controller; an extension with its own admin controller is picked up
+ # by the same walk, so nothing registers by hand.
+ #
+ # Re-registering a key replaces it, because the walk runs again on every
+ # code reload in development.
+ #
+ # @param key [String, Symbol] the resource key agents address it by
+ # @param model_name [String]
+ # @param permission [String] the `read_*` key gating it
+ # @param serializer_name [String]
+ # @param dashboard_path [String, nil] a `%<id>s` format string
+ # @param scope_name [Symbol, nil] narrows the model to a slice of itself
+ # @param write_permission [String, nil] the `write_*` key, absent when
+ # the controller offers no writes
+ # @param writable_attributes [Array<Symbol>] what a write may set
+ # @param create_workflow_key [String, nil] set when the controller
+ # declares a create workflow, which the generic write defers to
+ # @param update_workflow_key [String, nil] likewise for updates
+ # @return [Entry]
+ def register(key:, model_name:, permission:, serializer_name:, dashboard_path: nil, scope_name: nil,
+ write_permission: nil, writable_attributes: [], create_workflow_key: nil,
+ update_workflow_key: nil)
+ entry = Entry.new(key: key.to_s, model_name: model_name, permission: permission,
+ serializer_name: serializer_name, dashboard_path: dashboard_path,
+ scope_name: scope_name, write_permission: write_permission,
+ writable_attributes: writable_attributes,
+ create_workflow_key: create_workflow_key,
+ update_workflow_key: update_workflow_key)
+ entries[entry.key] = entry
+ end
+
+ # Forgets every registration, so the derivation can run again from
+ # scratch on a code reload.
+ #
+ # @return [void]
+ def reset!
+ @entries = {}
+ end
+
+ # @param key [String]
+ # @return [Entry, nil]
+ def find(key)
+ entries[key.to_s]
+ end
+
+ # Resources this caller may read, so a tool description lists only what
+ # they can actually ask about.
+ #
+ # @param context [Spree::AgentTools::Context]
+ # @return [Array<Entry>]
+ def available_for(context)
+ all.select { |entry| context.permitted?(entry.permission) }
+ end
+
+ private
+
+ def entries
+ @entries ||= {}
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools/workflow_schema.rb b/spree/core/lib/spree/agent_tools/workflow_schema.rb
new file mode 100644
index 0000000000..417d6b86b5
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/workflow_schema.rb
@@ -0,0 +1,235 @@
+module Spree
+ module AgentTools
+ # Reads a workflow's argument contract and turns it into a JSON parameter
+ # schema an agent can fill in.
+ #
+ # Nothing here is hand-maintained. `Method#parameters` on `perform` names
+ # every keyword and says which are required; the YARD `@param` block above
+ # it gives each one a type and a sentence of prose. Both already exist on
+ # every workflow, because the house style requires them — so a workflow
+ # gains a parameter and the tool's schema gains it in the same commit.
+ class WorkflowSchema
+ # A workflow that cannot be exposed as written. Raised at derivation time
+ # so the contract spec fails in CI rather than an agent meeting a broken
+ # tool in production.
+ class UndocumentedParameterError < StandardError
+ def initialize(workflow_class, names)
+ super("#{workflow_class} exposes #{names.join(', ')} without a YARD @param — " \
+ 'every parameter of an exposed workflow needs a documented type')
+ end
+ end
+
+ # Parameters the caller never supplies: they say who acted, and the
+ # answer is the authenticated principal, not something a model should be
+ # free to name. The adapter injects `context.principal` for whichever of
+ # these the workflow takes.
+ PRINCIPAL_PARAMETERS = %i[
+ canceler approver reviewer refunder created_by received_by
+ completed_by rejected_by accepted_by waived_by suspended_by
+ invited_by requested_by resolved_by denied_by verified_by
+ ].freeze
+
+ # YARD type to JSON type. A model type is handled separately — it becomes
+ # a prefixed-id string resolved through the resource map.
+ PRIMITIVES = {
+ 'String' => 'string',
+ 'Symbol' => 'string',
+ 'Time' => 'string',
+ 'DateTime' => 'string',
+ 'Date' => 'string',
+ 'Boolean' => 'boolean',
+ 'TrueClass' => 'boolean',
+ 'FalseClass' => 'boolean',
+ 'Integer' => 'integer',
+ 'Numeric' => 'number',
+ 'Float' => 'number',
+ 'BigDecimal' => 'number',
+ 'Hash' => 'object',
+ 'Array' => 'array'
+ }.freeze
+
+ # @return [Class] the workflow this schema describes
+ attr_reader :workflow_class
+
+ # @param workflow_class [Class]
+ # @param except [Array<Symbol>] parameters to leave out of the schema
+ def initialize(workflow_class, except: [])
+ @workflow_class = workflow_class
+ @except = except.map(&:to_sym)
+ end
+
+ # Every parameter the caller may supply, in `perform` order.
+ #
+ # @return [Array<Hash>] `{name:, required:, json_type:, model_name:, description:}`
+ def parameters
+ @parameters ||= begin
+ documented = docs
+ undocumented = keywords.keys - documented.keys - PRINCIPAL_PARAMETERS - @except
+ raise UndocumentedParameterError.new(workflow_class, undocumented) if undocumented.any?
+
+ keywords.filter_map do |name, required|
+ next if @except.include?(name) || PRINCIPAL_PARAMETERS.include?(name)
+
+ build_parameter(name, required, documented.fetch(name))
+ end
+ end
+ end
+
+ # The principal keywords this workflow accepts, so the adapter knows
+ # which to inject.
+ #
+ # @return [Array<Symbol>]
+ def principal_parameters
+ keywords.keys & PRINCIPAL_PARAMETERS
+ end
+
+ # @return [Hash] a JSON Schema object for the tool's arguments
+ def to_json_schema
+ properties = parameters.to_h do |parameter|
+ [parameter[:name].to_s, property_for(parameter)]
+ end
+
+ {
+ type: 'object',
+ properties: properties,
+ required: parameters.select { |parameter| parameter[:required] }.map { |parameter| parameter[:name].to_s }
+ }
+ end
+
+ private
+
+ # `perform`'s keywords, mapped to whether they are required.
+ #
+ # @return [Hash{Symbol => Boolean}]
+ def keywords
+ @keywords ||= workflow_class.instance_method(:perform).parameters.filter_map do |kind, name|
+ [name, kind == :keyreq] if %i[key keyreq].include?(kind)
+ end.to_h
+ end
+
+ def build_parameter(name, required, doc)
+ types = doc[:types]
+ model_name = types.find { |type| model_type?(type) }
+
+ {
+ name: name,
+ required: required,
+ model_name: model_name,
+ json_type: model_name ? 'string' : json_type_for(types),
+ description: description_for(doc[:description], model_name)
+ }
+ end
+
+ def property_for(parameter)
+ property = { type: parameter[:json_type] }
+ property[:description] = parameter[:description] if parameter[:description].present?
+ property[:items] = { type: 'object' } if parameter[:json_type] == 'array'
+ property
+ end
+
+ def description_for(text, model_name)
+ return text if model_name.blank?
+
+ prefix = "Prefixed id of the #{model_name.demodulize.underscore.humanize.downcase}"
+ text.present? ? "#{prefix} — #{text}" : prefix
+ end
+
+ # A Spree model, addressed by prefixed id. `Spree.admin_user_class` and
+ # the bare `Object` of a principal parameter are not: they never reach
+ # the schema, because principal parameters are stripped first.
+ def model_type?(type)
+ return false unless type.start_with?('Spree::')
+
+ constant = type.safe_constantize
+ constant.is_a?(Class) && constant < ActiveRecord::Base
+ end
+
+ def json_type_for(types)
+ concrete = types.reject { |type| type == 'nil' }
+ # `Array<Hash>` and friends — the outer container is what JSON sees.
+ concrete = concrete.map { |type| type.split('<').first }
+ concrete.filter_map { |type| PRIMITIVES[type] }.first || 'string'
+ end
+
+ # The YARD block above `perform`, parsed from the workflow's own source.
+ #
+ # Read from source rather than through the YARD gem: the gem is a
+ # development dependency, and this has to work in production, where the
+ # tool list is built on every request.
+ #
+ # @return [Hash{Symbol => Hash}]
+ def docs
+ @docs ||= self.class.parse_docs(workflow_class)
+ end
+
+ class << self
+ # Parsed once per workflow class and cached, because a tool list is
+ # built for every MCP request and the source never changes at runtime.
+ #
+ # @param workflow_class [Class]
+ # @return [Hash{Symbol => Hash}] `{types: [String], description: String}`
+ def parse_docs(workflow_class)
+ cache[workflow_class.name] ||= parse_source(workflow_class)
+ end
+
+ # @return [void]
+ def clear_cache!
+ @cache = {}
+ end
+
+ private
+
+ def cache
+ @cache ||= {}
+ end
+
+ def parse_source(workflow_class)
+ source = comment_above_perform(workflow_class)
+ return {} if source.blank?
+
+ parse_param_tags(source)
+ end
+
+ # The comment block immediately above `def perform`, joined so a
+ # `@param` whose prose wraps onto the next line keeps it.
+ def comment_above_perform(workflow_class)
+ location = workflow_class.instance_method(:perform).source_location
+ return if location.nil?
+
+ file, line = location
+ return unless File.exist?(file)
+
+ lines = File.readlines(file)
+ comment = []
+ index = line - 2
+ while index >= 0 && lines[index].strip.start_with?('#')
+ comment.unshift(lines[index].strip.delete_prefix('#').strip)
+ index -= 1
+ end
+ comment
+ end
+
+ def parse_param_tags(comment_lines)
+ tags = {}
+ current = nil
+
+ comment_lines.each do |line|
+ if (match = line.match(/\A@param\s+(\w+)\s+\[([^\]]*)\]\s*(.*)\z/))
+ current = match[1].to_sym
+ tags[current] = {
+ types: match[2].split(',').map(&:strip).reject(&:empty?),
+ description: match[3].strip
+ }
+ elsif line.start_with?('@')
+ current = nil
+ elsif current && line.present?
+ tags[current][:description] = [tags[current][:description], line].reject(&:blank?).join(' ')
+ end
+ end
+
+ tags
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools/workflow_tool.rb b/spree/core/lib/spree/agent_tools/workflow_tool.rb
new file mode 100644
index 0000000000..36fec7e857
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/workflow_tool.rb
@@ -0,0 +1,257 @@
+module Spree
+ module AgentTools
+ # One agent tool per exposed workflow.
+ #
+ # Every back-office write already goes through a workflow, so there is
+ # nothing to hand-write: the allowlist names a `Spree::Dependencies` key
+ # and a permission, {WorkflowSchema} reads the argument contract off the
+ # workflow's own `perform`, and this class resolves the arguments, injects
+ # the principal, takes the lock the controller takes and shapes the result.
+ #
+ # Generated classes are anonymous subclasses cached per dependency key, so
+ # a host app that swaps `Spree.order_cancel_workflow` for its own class
+ # keeps the tool and gets the replacement's schema.
+ class WorkflowTool < Spree::AgentTool
+ class_attribute :dependency_key, instance_accessor: false
+ class_attribute :schema_except, instance_accessor: false, default: [].freeze
+ class_attribute :summary_override, instance_accessor: false
+
+ class << self
+ # Builds (and caches) the tool class for one exposed workflow.
+ #
+ # @param dependency_key [Symbol] a `Spree::Dependencies` key
+ # @param permission [String] the `write_*` key gating it
+ # @param except [Array<Symbol>] parameters to hide
+ # @param summary [#call, nil] overrides the generated confirmation line
+ # @return [Class<WorkflowTool>, nil] nil when the key does not resolve
+ def for(dependency_key, permission:, except: [], summary: nil)
+ workflow_class = resolve_workflow(dependency_key)
+ return if workflow_class.nil?
+
+ cache_key = [dependency_key, workflow_class.name, permission, except, summary.object_id]
+ cache[cache_key] ||= build(dependency_key, workflow_class, permission, except, summary)
+ end
+
+ # @return [void]
+ def clear_cache!
+ @cache = {}
+ end
+
+ # The tool name for a dependency key: the workflow's dotted identity
+ # with dots as underscores, because MCP names allow only letters,
+ # digits, underscore and hyphen.
+ #
+ # @param workflow_class [Class]
+ # @return [String]
+ def tool_name_for(workflow_class)
+ workflow_class.workflow_key.tr('.', '_')
+ end
+
+ # @return [Class, nil]
+ def resolve_workflow(dependency_key)
+ Spree.public_send(dependency_key)
+ rescue NoMethodError, NameError
+ nil
+ end
+
+ # The workflow's own leading comment, first paragraph — what the class
+ # says it does, in the author's words rather than a second description
+ # kept in step by hand.
+ #
+ # @param workflow_class [Class]
+ # @return [String]
+ def description_for(workflow_class)
+ paragraph = leading_comment(workflow_class)
+ return "Runs the #{workflow_class.workflow_key.tr('.', ' ')} workflow." if paragraph.blank?
+
+ paragraph
+ end
+
+ private
+
+ def cache
+ @cache ||= {}
+ end
+
+ def build(dependency_key, workflow_class, permission_key, except, summary)
+ derived_schema = WorkflowSchema.new(workflow_class, except: except)
+ derived_name = tool_name_for(workflow_class)
+ derived_description = description_for(workflow_class)
+
+ Class.new(self) do
+ self.dependency_key = dependency_key
+ self.schema_except = except.freeze
+ self.summary_override = summary
+
+ tool_name derived_name
+ description derived_description
+ permission permission_key
+ mutating!
+
+ derived_schema.parameters.each do |parameter|
+ param parameter[:name],
+ type: parameter[:json_type].to_sym,
+ description: parameter[:description],
+ required: parameter[:required]
+ end
+ end
+ end
+
+ def leading_comment(workflow_class)
+ location = Object.const_source_location(workflow_class.name)
+ return if location.nil?
+
+ file, line = location
+ return unless file && File.exist?(file)
+
+ lines = File.readlines(file)
+ comment = []
+ index = line - 2
+ while index >= 0 && lines[index].strip.start_with?('#')
+ comment.unshift(lines[index].strip.delete_prefix('#').strip)
+ index -= 1
+ end
+ # First paragraph only — the rest is design rationale for readers of
+ # the class, not for a model choosing between tools.
+ comment.take_while(&:present?).join(' ').presence
+ end
+ end
+
+ # @return [Class] the workflow this tool runs, resolved now so a host
+ # app's replacement is picked up without a restart
+ def workflow_class
+ self.class.resolve_workflow(self.class.dependency_key)
+ end
+
+ # @return [WorkflowSchema]
+ def schema
+ @schema ||= WorkflowSchema.new(workflow_class, except: self.class.schema_except)
+ end
+
+ # Runs the workflow with the caller's arguments.
+ #
+ # Model-typed arguments arrive as prefixed ids and are resolved through
+ # the resource map under the context's store, so another store's id is
+ # simply not found. Principal parameters are never accepted from the
+ # caller — they are filled from the authenticated principal.
+ #
+ # @return [Hash] the result handed back to the model
+ def call(**arguments)
+ resolved = resolve_arguments(arguments)
+ return resolved if resolved.is_a?(Hash) && resolved[:error]
+
+ keywords = resolved.merge(principal_arguments)
+
+ run(keywords)
+ rescue ArgumentError => e
+ { error: e.message }
+ end
+
+ # One line saying what this tool did, for the client's confirmation
+ # prompt and the assistant's approval card.
+ #
+ # @param arguments [Hash]
+ # @return [String]
+ def summary(arguments)
+ return self.class.summary_override.call(context, arguments) if self.class.summary_override
+
+ action = workflow_class.workflow_key.tr('.', ' ').humanize
+ subject = subject_summary(arguments)
+ [action, subject].compact.join(' ')
+ end
+
+ private
+
+ def run(keywords)
+ subject = keywords.values.find { |value| value.is_a?(ActiveRecord::Base) }
+
+ result = with_subject_lock(subject) { workflow_class.call(**keywords) }
+
+ if result.success?
+ { summary: summary(keywords), record: record_result(result.value) }
+ else
+ { error: error_text(result) }
+ end
+ end
+
+ # The same row lock the admin controllers take for an order-subject
+ # workflow. Taken generically: whichever record the workflow is acting
+ # on is the one that must not change underneath it.
+ def with_subject_lock(subject, &)
+ return yield unless subject.respond_to?(:with_lock) && subject.persisted?
+
+ subject.with_lock(&)
+ end
+
+ def record_result(value)
+ return unless value.is_a?(ActiveRecord::Base)
+
+ entry = ResourceMap.all.find { |candidate| value.is_a?(candidate.model_class) }
+ return { id: value.try(:prefixed_id) } if entry.nil?
+
+ RecordSummary.call(entry: entry, record: value)
+ end
+
+ # The workflow's own refusal, in its own words, so the model can correct
+ # itself instead of retrying blind.
+ def error_text(result)
+ error = result.error
+ errors = error.respond_to?(:value) ? error.value : error
+
+ return errors.full_messages.to_sentence if errors.respond_to?(:full_messages) && errors.any?
+ return error.to_s if error.present?
+
+ 'The workflow refused the change.'
+ end
+
+ def principal_arguments
+ schema.principal_parameters.index_with { context.principal }
+ end
+
+ # Turns the caller's JSON arguments into what `perform` expects,
+ # resolving every model-typed parameter from its prefixed id.
+ #
+ # @return [Hash, Hash{Symbol => String}] keywords, or an `{error:}` result
+ def resolve_arguments(arguments)
+ resolved = {}
+
+ schema.parameters.each do |parameter|
+ name = parameter[:name]
+ next unless arguments.key?(name)
+
+ value = arguments[name]
+ next if value.nil?
+
+ if parameter[:model_name]
+ record = find_record(parameter[:model_name], value)
+ return { error: "No #{parameter[:model_name].demodulize.underscore.humanize.downcase} found for #{name} #{value.inspect}." } if record.nil?
+
+ resolved[name] = record
+ else
+ resolved[name] = value
+ end
+ end
+
+ resolved
+ end
+
+ # Resolves a prefixed id within the caller's store, through the resource
+ # map — so tenancy is answered the same way every read is.
+ def find_record(model_name, value)
+ entry = ResourceMap.all.find { |candidate| candidate.model_name == model_name }
+ relation = entry ? entry.scope_for(context) : model_name.constantize.for_store(context.store)
+
+ relation.find_by_prefix_id(value)
+ rescue StandardError
+ nil
+ end
+
+ def subject_summary(arguments)
+ record = arguments.values.find { |value| value.is_a?(ActiveRecord::Base) }
+ return if record.nil?
+
+ record.try(:number) || record.try(:name) || record.try(:prefixed_id)
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 3e54690c42..83ac93846d 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -512,6 +512,14 @@ module Spree
# @return [Spree::Reporting::Registry]
singleton_class.delegate :reporting, :reporting=, to: :spree_config
+ # The agent-tool registry — what an MCP client or the dashboard assistant
+ # may do on a merchant's behalf. A contract like +Spree.integrations+ and
+ # +Spree.reporting+: an extension registers a tool without depending on
+ # either adapter. See docs/plans/6.0-mcp-server.md.
+ #
+ # @return [Spree::AgentTools::Registry]
+ singleton_class.delegate :agent_tools, :agent_tools=, to: :spree_config
+
# The permission catalog — the grant vocabulary shared by staff roles and
# secret API key scopes. Roles themselves are data (Spree::Role#permissions);
# code only registers the vocabulary.
@@ -644,6 +652,8 @@ require 'spree/money'
require 'spree/service_module'
require 'spree/workflow'
require 'spree/reporting'
+require 'spree/agent_tool'
+require 'spree/agent_tools'
require 'spree/events'
require 'spree/store_scope_guard'
require 'spree/uploads'
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index b915fa70f5..95d77ef775 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -43,6 +43,7 @@ module Spree
:actor_classes,
:custom_fields,
:reporting,
+ :agent_tools,
:integrations,
:number_generators,
:subscribers,
@@ -158,6 +159,15 @@ module Spree
Spree::Reporting::DefaultVocabulary.install(app.config.spree.reporting)
end
+ # Seed the agent-tool registry before app initializers so applications
+ # and extensions can register their own tools and expose their own
+ # workflows in config/initializers (see docs/plans/6.0-mcp-server.md).
+ initializer 'spree.register.agent_tools', before: :load_config_initializers do |app|
+ app.config.spree.agent_tools = Spree::AgentTools::Registry.new
+ Spree::AgentTools::DefaultCatalog.install(app.config.spree.agent_tools)
+ end
+
+
# Country and subdivision names are translated by the countries gem, which
# only loads the locales it is told about. This runs after initialization
# because Spree.available_locales reads i18n configuration that is not
diff --git a/spree/core/spec/lib/spree/agent_tools/authorization_spec.rb b/spree/core/spec/lib/spree/agent_tools/authorization_spec.rb
new file mode 100644
index 0000000000..9b7a989476
--- /dev/null
+++ b/spree/core/spec/lib/spree/agent_tools/authorization_spec.rb
@@ -0,0 +1,74 @@
+require 'spec_helper'
+
+# Permission keys answer "may this admin touch products at all". They do not
+# answer "which products". A host app narrows that with a record-level ability
+# rule, the Admin API honours it, and so must the assistant — otherwise a
+# seller asks the assistant and sees the whole store.
+RSpec.describe 'assistant authorization' do
+ let(:store) { @default_store }
+ let(:admin) { create(:admin_user) }
+ let(:context) { Spree::Assistant::Context.new(store: store, user: admin, ability: ability) }
+
+ let!(:visible) { create(:product, store: store, name: 'Visible Product', status: 'active') }
+ let!(:hidden) { create(:product, store: store, name: 'Hidden Product', status: 'active') }
+
+ # Stands in for a host app's record-level rule: this admin may see and edit
+ # one product, not the other.
+ let(:ability) do
+ Class.new do
+ include CanCan::Ability
+
+ def initialize(allowed)
+ can :manage, Spree::Product, id: allowed.id
+ end
+
+ def permission_keys
+ Spree.permissions.catalog_keys
+ end
+ end.new(visible)
+ end
+
+ describe 'reads' do
+ it 'hides records the ability excludes' do
+ result = Spree::Assistant::Tools::SearchResources.new(context).call(resource: 'products', limit: 25)
+ titles = result[:records].map { |record| record[:title] }
+
+ expect(titles).to include('Visible Product')
+ expect(titles).not_to include('Hidden Product')
+ end
+
+ it 'counts only what the admin may see' do
+ result = Spree::Assistant::Tools::SearchResources.new(context).call(resource: 'products')
+
+ # The assistant states this number out loud, so a leak here is a leak the
+ # merchant reads.
+ expect(result[:total]).to eq(1)
+ end
+
+ it 'cannot fetch an excluded record directly' do
+ result = Spree::Assistant::Tools::GetResource.new(context).
+ call(resource: 'products', id: hidden.prefixed_id)
+
+ expect(result[:error]).to be_present
+ expect(result[:record]).to be_nil
+ end
+ end
+
+ describe 'changes' do
+ it 'refuses a record the ability excludes' do
+ result = Spree::Assistant::Tools::UpdateProductStatus.new(context).
+ call(id: hidden.slug, status: 'draft')
+
+ expect(result[:error]).to be_present
+ expect(hidden.reload.status).to eq('active')
+ end
+
+ it 'allows a record the ability includes' do
+ result = Spree::Assistant::Tools::UpdateProductStatus.new(context).
+ call(id: visible.slug, status: 'draft')
+
+ expect(result[:ok]).to be(true)
+ expect(visible.reload.status).to eq('draft')
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/agent_tools/record_summary_spec.rb b/spree/core/spec/lib/spree/agent_tools/record_summary_spec.rb
new file mode 100644
index 0000000000..8019995756
--- /dev/null
+++ b/spree/core/spec/lib/spree/agent_tools/record_summary_spec.rb
@@ -0,0 +1,51 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Assistant::RecordSummary do
+ # Every record the assistant emits crosses the wire to a third-party AI vendor
+ # and is stored in chat history, so this filter is the last thing standing
+ # between a serializer that gains a credential field and a live secret leaving
+ # the building.
+ describe '.sanitize' do
+ it 'drops credential-shaped keys' do
+ result = described_class.sanitize(
+ 'name' => 'Keep me',
+ 'api_key' => 'sk-live-LEAK',
+ 'webhook_secret' => 'whsec_LEAK',
+ 'access_token' => 'LEAK',
+ 'password_digest' => 'LEAK'
+ )
+
+ expect(result.keys).to contain_exactly('name')
+ end
+
+ it 'reaches inside nested associations' do
+ # Serializers nest — an order carries a market, a customer carries
+ # addresses. A shallow filter scrubbed the top level and forwarded
+ # whatever sat one layer down.
+ result = described_class.sanitize(
+ 'number' => 'R1001',
+ 'market' => { 'name' => 'EU', 'api_key' => 'sk-live-LEAK' },
+ 'payments' => [{ 'amount' => '10', 'token' => 'LEAK' }]
+ )
+
+ expect(result.to_s).not_to include('LEAK')
+ expect(result['market']['name']).to eq('EU')
+ expect(result['payments'].first['amount']).to eq('10')
+ end
+
+ it 'drops a gift card wholesale, because its code is the bearer instrument' do
+ result = described_class.sanitize('number' => 'R1', 'gift_card' => { 'code' => 'GC-SPENDABLE' })
+
+ expect(result).not_to have_key('gift_card')
+ expect(result['number']).to eq('R1')
+ end
+
+ it 'keeps a code that is an identifier rather than a secret' do
+ # Channels, promotions and commission rates all use `code` as a name a
+ # merchant asks about; blanket-stripping it would break real answers.
+ result = described_class.sanitize('code' => 'freeship', 'name' => 'Free shipping')
+
+ expect(result['code']).to eq('freeship')
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/agent_tools/resource_map_spec.rb b/spree/core/spec/lib/spree/agent_tools/resource_map_spec.rb
new file mode 100644
index 0000000000..9636cf74ae
--- /dev/null
+++ b/spree/core/spec/lib/spree/agent_tools/resource_map_spec.rb
@@ -0,0 +1,106 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Assistant::ResourceMap do
+ let(:store) { @default_store }
+ let(:admin) { create(:admin_user) }
+ let(:context) do
+ Spree::Assistant::Context.new(store: store, user: admin, ability: full_ability)
+ end
+ let(:full_ability) do
+ Class.new do
+ include CanCan::Ability
+ def initialize = can(:manage, :all)
+ def permission_keys = Spree.permissions.catalog_keys
+ end.new
+ end
+
+ # Every entry is a promise the assistant makes to the model: this resource
+ # exists, is searchable, and links somewhere real. A typo in any of the four
+ # fields is invisible until a merchant asks the question that needs it.
+ describe 'every registered resource' do
+ Spree::Assistant::ResourceMap.all.each do |entry|
+ context "`#{entry.key}`" do
+ it 'names a model that exists' do
+ expect(entry.model_name.safe_constantize).to be_present
+ end
+
+ it 'names an admin serializer that exists' do
+ expect(entry.serializer_name.safe_constantize).to be_present
+ end
+
+ it 'declares a permission key in the catalog' do
+ expect(Spree.permissions.key?(entry.permission)).to be(true),
+ "#{entry.key} declares unknown permission #{entry.permission.inspect}"
+ end
+
+ it 'builds a working store-scoped relation' do
+ expect { entry.scope_for(context).count }.not_to raise_error
+ end
+
+ it 'exposes filterable fields' do
+ expect(entry.filterable_fields).to be_present
+ end
+ end
+ end
+ end
+
+ describe 'a resource that is a slice of a model' do
+ it 'narrows through its scope' do
+ draft_orders = described_class.find('draft_orders')
+ orders = described_class.find('orders')
+
+ expect(draft_orders.model_name).to eq(orders.model_name)
+ expect(draft_orders.scope_for(context).to_sql).not_to eq(orders.scope_for(context).to_sql)
+ end
+ end
+
+ describe 'store scoping' do
+ it 'reaches customers, which have no Store association' do
+ # Customers are global; `for_store` is how the Admin API scopes them, and
+ # the reason this map uses it rather than a Store association.
+ expect { described_class.find('customers').scope_for(context).count }.not_to raise_error
+ end
+ end
+end
+
+RSpec.describe Spree::Assistant::ResourceMap, 'permission alignment' do
+ # A resource must not be reachable through the assistant on a looser key than
+ # the Admin API demands for the same records — otherwise an admin can ask the
+ # assistant for something the dashboard would refuse them, and the permission
+ # layer (the one an operator reads and reasons about) is silently wrong.
+ #
+ # Derived from the map rather than a hand-kept list: a list only covers the
+ # resources someone remembered to add, so a permission renamed in core drifts
+ # silently on every resource outside it — which is exactly how
+ # `delivery_methods` came to sit on `read_settings` while its controller
+ # demanded `read_delivery_methods`.
+ #
+ # Resources whose controller resolves its permission per record (imports and
+ # exports, keyed by import type) have nothing static to compare against, and
+ # ones the Admin API serves from a differently-named controller are named
+ # here with the controller that actually answers for them.
+ DYNAMIC_PERMISSION = %w[imports exports].freeze
+ CONTROLLER_OVERRIDES = { 'draft_orders' => 'OrdersController' }.freeze
+
+ described_class.all.each do |entry|
+ next if DYNAMIC_PERMISSION.include?(entry.key)
+
+ controller_name = CONTROLLER_OVERRIDES.fetch(entry.key) { "#{entry.key.camelize}Controller" }
+
+ it "`#{entry.key}` uses the same permission as #{controller_name}" do
+ controller = "Spree::Api::V3::Admin::#{controller_name}".safe_constantize
+ skip("#{controller_name} not found") if controller.nil?
+
+ scoped = controller._scoped_resource
+ skip("#{controller_name} declares no scoped_resource") if scoped.blank?
+
+ expect(entry.permission).to eq("read_#{scoped}")
+ end
+ end
+
+ it 'points every resource at a permission the catalog actually defines' do
+ unknown = described_class.all.reject { |entry| Spree.permissions.key?(entry.permission) }
+
+ expect(unknown.map(&:key)).to be_empty
+ end
+end
diff --git a/spree/core/spec/tools/spree/agent_tools/create_export_spec.rb b/spree/core/spec/tools/spree/agent_tools/create_export_spec.rb
new file mode 100644
index 0000000000..e270f30ecf
--- /dev/null
+++ b/spree/core/spec/tools/spree/agent_tools/create_export_spec.rb
@@ -0,0 +1,65 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Assistant::Tools::CreateExport do
+ subject(:tool) { described_class.new(context) }
+
+ let(:store) { @default_store }
+ let(:admin) { create(:admin_user) }
+ let(:context) { Spree::Assistant::Context.new(store: store, user: admin, ability: ability) }
+ let(:ability) do
+ Class.new do
+ include CanCan::Ability
+ def initialize = can(:manage, :all)
+ def permission_keys = Spree.permissions.catalog_keys
+ end.new
+ end
+
+ it 'is held for approval — the file leaves the building' do
+ expect(described_class.mutating?).to be(true)
+ end
+
+ it 'creates an export owned by the asking admin' do
+ result = tool.call(resource: 'products')
+
+ expect(result[:ok]).to be(true)
+ export = Spree::Export.find_by_prefix_id(result[:id])
+ # The export builds its ability from this user, so the file contains what
+ # that admin could see and nothing more.
+ expect(export.user).to eq(admin)
+ expect(export.store).to eq(store)
+ end
+
+ it 'carries the filters through to the export' do
+ result = tool.call(resource: 'products', filters: { 'status_eq' => 'active' })
+
+ export = Spree::Export.find_by_prefix_id(result[:id])
+ # Stored as a JSON string, which is how the Admin API persists it too.
+ expect(export.search_params.to_s).to include('status_eq', 'active')
+ end
+
+ it 'refuses a resource Spree cannot export, and says what it can' do
+ result = tool.call(resource: 'invoices')
+
+ expect(result[:error]).to include('invoices')
+ expect(result[:available]).to include('products', 'orders')
+ end
+
+ context 'when the admin may not read the resource' do
+ let(:ability) do
+ Class.new do
+ include CanCan::Ability
+ def initialize = can(:manage, :all)
+ def permission_keys = %w[read_products]
+ end.new
+ end
+
+ it 'refuses to export it' do
+ # Exporting is a read of every matching record, so it needs the same
+ # permission reading them would.
+ result = tool.call(resource: 'orders')
+
+ expect(result[:error]).to include('permission')
+ expect(Spree::Export.count).to be_zero
+ end
+ end
+end
diff --git a/spree/core/spec/tools/spree/agent_tools/import_tools_spec.rb b/spree/core/spec/tools/spree/agent_tools/import_tools_spec.rb
new file mode 100644
index 0000000000..5df9d1ef7f
--- /dev/null
+++ b/spree/core/spec/tools/spree/agent_tools/import_tools_spec.rb
@@ -0,0 +1,99 @@
+require 'spec_helper'
+require 'csv'
+
+RSpec.describe 'assistant import tools' do
+ let(:store) { @default_store }
+ let(:admin) { create(:admin_user) }
+ let(:context) { Spree::Assistant::Context.new(store: store, user: admin, ability: ability) }
+ let(:ability) do
+ Class.new do
+ include CanCan::Ability
+ def initialize = can(:manage, :all)
+ def permission_keys = Spree.permissions.catalog_keys
+ end.new
+ end
+
+ # A spreadsheet with the headings a real merchant would send: none of them
+ # match a Spree field name, which is the whole reason this feature exists.
+ let(:csv) do
+ CSV.generate do |rows|
+ rows << ['Handle', 'Product Title', 'Item Code', 'Retail Price (inc VAT)']
+ rows << ['blue-shirt', 'Blue Shirt', 'BS-1', '29.00']
+ end
+ end
+
+ let(:import) do
+ record = Spree::Imports::Products.new(owner: store, user: admin)
+ record.attachment.attach(io: StringIO.new(csv), filename: 'messy.csv', content_type: 'text/csv')
+ record.save!
+ record.start_mapping!
+ record
+ end
+
+ describe Spree::Assistant::Tools::DescribeImportMapping do
+ it 'hands the model the real headings and the real field names' do
+ result = described_class.new(context).call(id: import.prefixed_id)
+
+ expect(result[:file_columns]).to include('Product Title', 'Item Code')
+ expect(result[:spree_fields].map { |field| field[:field] }).to include('name', 'sku', 'price')
+ expect(result[:spree_fields].select { |field| field[:required] }.map { |f| f[:field] })
+ .to contain_exactly('slug', 'sku', 'name', 'price')
+ end
+ end
+
+ describe Spree::Assistant::Tools::ProposeImportMapping do
+ subject(:tool) { described_class.new(context) }
+
+ it 'is held for approval rather than applied outright' do
+ expect(described_class.mutating?).to be(true)
+ end
+
+ it 'applies a mapping and reports what is still missing' do
+ result = tool.call(id: import.prefixed_id,
+ mapping: { 'name' => 'Product Title', 'sku' => 'Item Code' })
+
+ expect(result[:ok]).to be(true)
+ expect(import.mappings.find_by(schema_field: 'name').file_column).to eq('Product Title')
+ expect(result[:still_missing]).to contain_exactly('slug', 'price')
+ end
+
+ it 'starts the import once every required field is mapped' do
+ import.update!(preferred_inline: true)
+
+ tool.call(id: import.prefixed_id,
+ mapping: { 'slug' => 'Handle', 'name' => 'Product Title',
+ 'sku' => 'Item Code', 'price' => 'Retail Price (inc VAT)' })
+
+ expect(import.reload.status).to eq('completed')
+ end
+
+ it 'refuses a field or column that does not exist' do
+ # The model is guessing at a messy file; an invented pairing must not
+ # reach the database, and it needs the real vocabulary to correct itself.
+ result = tool.call(id: import.prefixed_id,
+ mapping: { 'invented' => 'Product Title', 'name' => 'No Such Column' })
+
+ expect(result[:error]).to be_present
+ expect(result[:spree_fields]).to include('name')
+ expect(import.mappings.find_by(schema_field: 'name').file_column).to be_blank
+ end
+
+ it 'names the pairing on the approval card' do
+ summary = tool.summary(id: import.prefixed_id, mapping: { 'name' => 'Product Title' })
+
+ # The merchant judges this sentence, so it reads as the pairing itself.
+ expect(summary).to eq('Map Product Title → name')
+ end
+ end
+
+ describe Spree::Assistant::Tools::GetImportStatus do
+ it 'reports row counts for the latest import' do
+ import
+
+ result = described_class.new(context).call
+
+ expect(result[:number]).to eq(import.number)
+ expect(result[:status]).to eq('mapping')
+ end
+ end
+end
diff --git a/spree/core/spec/tools/spree/agent_tools/search_resources_spec.rb b/spree/core/spec/tools/spree/agent_tools/search_resources_spec.rb
new file mode 100644
index 0000000000..dd8a066852
--- /dev/null
+++ b/spree/core/spec/tools/spree/agent_tools/search_resources_spec.rb
@@ -0,0 +1,151 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Assistant::Tools::SearchResources do
+ subject(:tool) { described_class.new(context) }
+
+ let(:store) { @default_store }
+ let(:admin) { create(:admin_user) }
+ let(:context) { Spree::Assistant::Context.new(store: store, user: admin, ability: ability) }
+ let(:ability) { full_ability_for(admin) }
+ # A real ability rather than a double: the tools now call `accessible_by`,
+ # which needs CanCanCan's actual machinery. `admin` here is a full admin, so
+ # this grants everything — record-level narrowing is exercised in
+ # spec/authorization_spec.rb.
+ def full_ability_for(user)
+ Class.new do
+ include CanCan::Ability
+
+ def initialize
+ can :manage, :all
+ end
+
+ def permission_keys
+ Spree.permissions.catalog_keys
+ end
+ end.new
+ end
+
+
+ let!(:products) { create_list(:product, 3, store: store, status: 'active') }
+
+ describe 'counts' do
+ it 'reports how many matched, not how many were returned' do
+ result = tool.call(resource: 'products', limit: 2)
+
+ # The assistant is asked to state this number; the page size would have
+ # it answer "2 products" for a store holding three.
+ expect(result[:total]).to eq(3)
+ expect(result[:count]).to eq(2)
+ expect(result[:records].size).to eq(2)
+ end
+ end
+
+ describe 'records' do
+ it 'carries a title and a dashboard path for each row' do
+ record = tool.call(resource: 'products', limit: 1)[:records].first
+
+ expect(record[:id]).to start_with('prod_')
+ expect(record[:title]).to be_present
+ expect(record[:path]).to match(%r{\A/products/prod_})
+ end
+ end
+
+ describe 'filters' do
+ it 'accepts a named scope' do
+ result = tool.call(resource: 'products', filters: { 'in_stock' => true })
+
+ expect(result[:error]).to be_nil
+ expect(result[:total]).to eq(store.products.in_stock.count)
+ end
+
+ it 'refuses an invented filter instead of silently ignoring it' do
+ # Ransack drops unknown conditions, so without this the search widens to
+ # everything and the result reads as a match.
+ result = tool.call(resource: 'products', filters: { 'imaginary_field_eq' => 'x' })
+
+ expect(result[:error]).to include('imaginary_field_eq')
+ expect(result[:filterable_fields]).to include('name')
+ expect(result[:records]).to be_nil
+ end
+ end
+
+ describe 'store scoping' do
+ # An explicit code: the factory's default collides with the suite-wide
+ # default store.
+ let(:other_store) { create(:store, code: "other-#{SecureRandom.hex(4)}") }
+
+ it 'never reaches another store\'s records' do
+ create(:product, store: other_store, name: 'Not Yours')
+
+ titles = tool.call(resource: 'products', limit: 25)[:records].map { |r| r[:title] }
+
+ expect(titles).not_to include('Not Yours')
+ end
+ end
+
+ describe 'permissions' do
+ # Can read products but holds no order permission — the tool must refuse
+ # the resource before it ever builds a query.
+ let(:ability) do
+ Class.new do
+ include CanCan::Ability
+ def initialize = can(:manage, :all)
+ def permission_keys = %w[read_products]
+ end.new
+ end
+
+ it 'refuses a resource the admin may not read' do
+ result = tool.call(resource: 'orders')
+
+ expect(result[:error]).to include('permission')
+ end
+ end
+end
+
+RSpec.describe Spree::Assistant::Tools::SearchResources, 'filter validation' do
+ subject(:tool) { described_class.new(context) }
+
+ let(:store) { @default_store }
+ let(:admin) { create(:admin_user) }
+ let(:context) { Spree::Assistant::Context.new(store: store, user: admin, ability: ability) }
+ let(:ability) do
+ Class.new do
+ include CanCan::Ability
+ def initialize = can(:manage, :all)
+ def permission_keys = Spree.permissions.catalog_keys
+ end.new
+ end
+
+ let!(:products) { create_list(:product, 3, store: store, status: 'active') }
+
+ # Ransack runs with `ignore_unknown_conditions` on, so a key it cannot parse
+ # is dropped and the search returns everything — which the assistant then
+ # reports as the answer. Checking only the attribute half let this through.
+ it 'refuses a real attribute with an invented predicate' do
+ result = tool.call(resource: 'products', filters: { 'status_notarealpredicate' => 'x' })
+
+ expect(result[:error]).to include('status_notarealpredicate')
+ expect(result[:total]).to be_nil
+ end
+
+ it 'still accepts every real predicate' do
+ %w[name_cont status_eq created_at_gteq].each do |key|
+ result = tool.call(resource: 'products', filters: { key => 'active' })
+
+ expect(result[:error]).to be_nil, "#{key} was rejected: #{result[:error]}"
+ end
+ end
+
+ it 'accepts a bare attribute, which Ransack reads as eq' do
+ expect(tool.call(resource: 'products', filters: { 'status' => 'active' })[:error]).to be_nil
+ end
+
+ it 'keeps `false` as a filter value rather than discarding it' do
+ # `compact_blank` threw this away, so the search silently returned
+ # everything instead of filtering.
+ result = tool.call(resource: 'products', filters: { 'out_of_stock' => false })
+
+ expect(result[:error]).to be_nil
+ expect(result[:total]).to eq(store.products.out_of_stock(false).count)
+ end
+end