Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Let the generic agent tools reach records nested under another (V-3779) (#15094)
Damian Legawiecf7588f0edc8d
diff --git a/docs/developer/mcp/tools.mdx b/docs/developer/mcp/tools.mdxindex 055f986ab0..88734851a8 100644--- a/docs/developer/mcp/tools.mdx+++ b/docs/developer/mcp/tools.mdx@@ -126,6 +126,12 @@ The dash is the point: each call is gated on the resource being written, so aconnection approved for products can create a product and is refused a market.Call `describe_resource` for what a resource accepts.+Some records exist only inside another: an order's items, discounts and fees.+`describe_resource` names that record as the resource's `parent`, and each+generic tool that reads or writes a record takes its id as `parent_id`. That is+how an assistant changes a quantity, sets a negotiated unit price or adds a+discount on a draft order.+## Resources@@ -158,7 +164,7 @@ Two things worth knowing about the generic writes:**Rows selected by a `type` take a short name, never a class name.** A promotion's rules and actions, a price list's rules and a payment method's provider are chosen by `type`: `item_total`, `create_item_adjustments`, `check`. `describe_resource` on one resource lists the kinds under `types` and `nested_types`, each with the schema its `preferences` follow and, for an action that prices a discount, the calculators it takes. A kind the store does not offer is refused with the accepted ones named, so nothing is saved with a rule or an action missing.-**Rows that live under a parent are reached through it.** Promotion rules, promotion actions and an order's payments have no search of their own: read them with `get_resource` on the parent, naming the list in `expand`. Where the parent accepts the rows as a list attribute, as a promotion does its `rules` and `actions`, that attribute is also how they are written.+**Rows that live under a parent are reached through it.** Promotion rules, promotion actions and an order's payments have no search of their own: pass the parent's id as `parent_id`, or read them with `get_resource` on the parent, naming the list in `expand`. Where the parent accepts the rows as a list attribute, as a promotion does its `rules` and `actions`, that attribute is also how they are written.## See alsodiff --git a/spree/api/spec/lib/spree/agent_tools/resource_map_spec.rb b/spree/api/spec/lib/spree/agent_tools/resource_map_spec.rbindex b6bd0a5e81..b7bc86a830 100644--- a/spree/api/spec/lib/spree/agent_tools/resource_map_spec.rb+++ b/spree/api/spec/lib/spree/agent_tools/resource_map_spec.rb@@ -88,6 +88,20 @@ RSpec.describe Spree::AgentTools::ResourceMap doexpect(described_class.find('line_items').api_path(:index)).to include(':')end+ # A `?` would end the path, sending a line item's delete to the order.+ it 'keeps a caller-supplied id inside its own segment' do+ path = described_class.find('line_items').path_for(:destroy, id: 'li_1', parent_id: 'or_1?x=y')++ expect(path).to end_with('/orders/or_1%3Fx%3Dy/items/li_1')+ end++ it 'refuses a path it cannot fill completely' do+ entry = described_class.find('line_items')+ allow(entry).to receive(:api_path).and_return('/api/v3/admin/stores/:store_id/orders/:order_id/items/:id')++ expect(entry.path_for(:show, id: 'li_1', parent_id: 'or_1')).to be_nil+ end+it 'knows which resources a tool can dispatch to' doexpect(described_class.find('products')).to be_dispatchableexpect(described_class.find('imports')).not_to be_dispatchablediff --git a/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rbindex e11ebe94f6..5e913ab5a1 100644--- a/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb@@ -110,6 +110,43 @@ RSpec.describe 'agent generic record writes' doendend+ # An order's items, discounts and fees exist only under their order, so+ # the generic tools take the order as parent_id and fill it into the path.+ describe 'a resource nested under an order' do+ let(:order) { create(:order_with_line_items, store: store, line_items_count: 1) }+ let(:line_item) { order.line_items.first }+ let(:items_key) { Spree::AgentTools::ResourceMap.all.find { |entry| entry.model_name == 'Spree::LineItem' }.key }++ it 'changes a line through its order' do+ result = tool('update_resource').call(resource: items_key, id: line_item.prefixed_id,+ parent_id: order.prefixed_id, attributes: { 'quantity' => 4 })++ expect(result[:error]).to be_nil+ expect(line_item.reload.quantity).to eq(4)+ end++ it 'lists the lines of one order' do+ result = tool('search_resources').call(resource: items_key, parent_id: order.prefixed_id)++ expect(result[:error]).to be_nil+ expect(result[:total]).to eq(1)+ end++ it 'asks for the order rather than calling a path with a hole in it' do+ result = tool('update_resource').call(resource: items_key, id: line_item.prefixed_id,+ attributes: { 'quantity' => 4 })++ expect(result[:error]).to include('parent_id')+ expect(line_item.reload.quantity).not_to eq(4)+ end++ it 'is described with the record it belongs to' do+ described = tool('describe_resource').call(resource: items_key)[:resources].first++ expect(described[:parent]).to eq('orders')+ end+ end+# The write tools tell the caller to call describe_resource for the# attributes a resource accepts, so it has to answer that question.describe 'describe_resource and the write tools agree' do@@ -398,11 +435,28 @@ RSpec.describe 'agent generic record writes' do# A resource that only exists under a parent has no path a tool can fill# in. Dispatching the template as it stood answered "Promotion not found",# which a model reported as a fact about the store.+ describe 'the summary of a create' do+ it 'names the parent only for a resource nested under one' do+ create = tool('create_resource')++ expect(create.summary(resource: 'products', attributes: { name: 'Mug' }, parent_id: 'or_1')).to eq('Create product Mug')+ expect(create.summary(resource: 'line_items', attributes: {}, parent_id: 'or_1')).to eq('Create line item under or_1')+ end+ end++ describe 'a top-level record with no id' do+ it 'asks for the id rather than failing' do+ result = tool('get_resource').call(resource: 'products', id: '')++ expect(result[:error]).to include('Pass the id of the product')+ end+ end+describe 'a resource reached only under a parent' doit 'is not searched on its own, and says where its rows live' doresult = tool('search_resources').call(resource: 'promotion_rules')- expect(result[:error]).to include('belong to a promotion', 'rules attribute of promotions', 'expand: ["rules"]')+ expect(result[:error]).to include('belong to a promotion', 'rules attribute of promotions', 'expand: ["rules"]', 'as parent_id')expect(result[:available]).to include('promotions')expect(result[:available]).not_to include('promotion_rules')enddiff --git a/spree/core/app/tools/spree/agent_tools/create_resource.rb b/spree/core/app/tools/spree/agent_tools/create_resource.rbindex 1bd71e612a..81ae28dcd4 100644--- a/spree/core/app/tools/spree/agent_tools/create_resource.rb+++ b/spree/core/app/tools/spree/agent_tools/create_resource.rb@@ -13,23 +13,31 @@ module Spreeparam :resource, description: 'Resource key — call describe_resource for the list', required: trueparam :attributes, type: :object, description: 'Attributes to set on the new record', required: true+ param :parent_id, description: PARENT_ID_DESCRIPTION- def call(resource:, attributes: {})+ def call(resource:, attributes: {}, parent_id: nil)entry, refusal = writable_entry(resource, :create)return refusal if refusalbody, rejection = body_for(entry, attributes)return rejection if rejection- response = dispatch.call(method: :post, path: entry.api_path(:create), body: body)+ path, missing = write_path(entry, :create, parent_id: parent_id)+ return missing if missing- result_for(response, entry, summary: summary(resource: resource, attributes: attributes))+ response = dispatch.call(method: :post, path: path, body: body)++ result_for(response, entry, summary: summary(resource: resource, attributes: attributes, parent_id: parent_id))enddef summary(arguments)named = arguments[:attributes].to_h.values_at('name', :name, 'number', :number).compact.first- "Create #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{named}".strip+ line = "Create #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{named}".strip++ # A top-level resource ignores parent_id, so the approval card does too.+ nested = arguments[:parent_id].present? && ResourceMap.find(arguments[:resource])&.parent_param(:create)+ nested ? "#{line} under #{arguments[:parent_id]}" : lineendendenddiff --git a/spree/core/app/tools/spree/agent_tools/delete_resource.rb b/spree/core/app/tools/spree/agent_tools/delete_resource.rbindex b2611154c4..a9a0b809d3 100644--- a/spree/core/app/tools/spree/agent_tools/delete_resource.rb+++ b/spree/core/app/tools/spree/agent_tools/delete_resource.rb@@ -9,19 +9,27 @@ module Spreeparam :resource, description: 'Resource key — call describe_resource for the list', required: trueparam :id, description: 'The record id as shown in search results', required: true+ param :parent_id, description: PARENT_ID_DESCRIPTION- def call(resource:, id:)+ def call(resource:, id:, parent_id: nil)entry, refusal = writable_entry(resource, :destroy)return refusal if refusal- response = dispatch.call(method: :delete, path: entry.api_path(:destroy).sub(':id', id.to_s))+ path, missing = write_path(entry, :destroy, id: id, parent_id: parent_id)+ return missing if missing++ response = dispatch.call(method: :delete, path: path)return { error: response.error_message } unless response.success?- { summary: summary(resource: resource, id: id) }+ { summary: summary(resource: resource, id: id, parent_id: parent_id) }enddef summary(arguments)- "Delete #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{arguments[:id]}"+ line = "Delete #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{arguments[:id]}"+ # The approval card is all a merchant sees, so a nested delete names+ # the record it runs under, as a nested create does.+ nested = arguments[:parent_id].present? && ResourceMap.find(arguments[:resource])&.parent_param(:destroy)+ nested ? "#{line} under #{arguments[:parent_id]}" : lineendendenddiff --git a/spree/core/app/tools/spree/agent_tools/describe_resource.rb b/spree/core/app/tools/spree/agent_tools/describe_resource.rbindex 69e41b9afd..9bd4c0c36b 100644--- a/spree/core/app/tools/spree/agent_tools/describe_resource.rb+++ b/spree/core/app/tools/spree/agent_tools/describe_resource.rb@@ -87,6 +87,10 @@ module Spreedef describe(entry, detailed:){resource: entry.key,+ # A resource reached through another record — an order's items, a+ # product's variants when written — needs that record's id as+ # parent_id on the calls whose route runs under it.+ parent: %i[index create update].lazy.filter_map { |action| entry.parent_key(action) }.first,filterable_fields: entry.filterable_fields,# What a generic write accepts, so the model learns the schema here# rather than by sending an invalid write and reading the refusal —diff --git a/spree/core/app/tools/spree/agent_tools/get_resource.rb b/spree/core/app/tools/spree/agent_tools/get_resource.rbindex efc95c9e22..d3c84f9b3a 100644--- a/spree/core/app/tools/spree/agent_tools/get_resource.rb+++ b/spree/core/app/tools/spree/agent_tools/get_resource.rb@@ -14,21 +14,23 @@ module Spreeparam :id, description: 'The record id as shown in search results', required: trueparam :expand, type: :array, items: :string,description: "Associations to include, e.g. [\"variants\"] on a product"+ param :parent_id, description: PARENT_ID_DESCRIPTION- def call(resource:, id:, expand: nil)+ def call(resource:, id:, expand: nil, parent_id: nil)entry = ResourceMap.find(resource)return unknown_resource(resource) if entry.nil?return { error: "You do not have permission to read #{entry.key}." } unlesscontext.permitted?(entry.permission)- path = entry.api_path(:show)- return { error: "#{entry.key} cannot be fetched one at a time." } if path.blank?- return nested_resource_error(entry, 'fetched', :show) if entry.nested?(:show)+ return { error: "#{entry.key} cannot be fetched one at a time." } if entry.api_path(:show).blank?++ path = entry.path_for(:show, id: id, parent_id: parent_id)+ return nested_resource_error(entry, 'fetched', :show) if path.nil?requested, refusal = expansions(entry, expand)return refusal if refusal- response = dispatch.call(method: :get, path: path.sub(':id', id.to_s),+ response = dispatch.call(method: :get, path: path,params: requested.any? ? { expand: requested.join(',') } : {})return { error: not_found(entry, id, response) } unless response.success?diff --git a/spree/core/app/tools/spree/agent_tools/resource_write.rb b/spree/core/app/tools/spree/agent_tools/resource_write.rbindex e4ee2a04ab..0e0c3112de 100644--- a/spree/core/app/tools/spree/agent_tools/resource_write.rb+++ b/spree/core/app/tools/spree/agent_tools/resource_write.rb@@ -41,7 +41,6 @@ module Spreepath = entry.api_path(action)return [nil, { error: not_writable(entry, action) }] if path.blank?- return [nil, nested_resource_error(entry, verb_for(action), action)] if entry.nested?(action)# The endpoint answers 403 for a scope the credential lacks, in its# own words. This check only avoids offering a tool that cannot work@@ -78,6 +77,17 @@ module Spreeaccepted_attributes: accepted }]end+ # The path for this write, or the refusal saying which record a nested+ # resource needs.+ #+ # @return [Array(String, nil), Array(nil, Hash)]+ def write_path(entry, action, id: nil, parent_id: nil)+ path = entry.path_for(action, id: id, parent_id: parent_id)+ return [path, nil] if path++ [nil, nested_resource_error(entry, verb_for(action), action)]+ end+def result_for(response, entry, summary:)return { error: response.error_message } unless response.success?diff --git a/spree/core/app/tools/spree/agent_tools/search_resources.rb b/spree/core/app/tools/spree/agent_tools/search_resources.rbindex c97b4d838f..eeaff0c58f 100644--- a/spree/core/app/tools/spree/agent_tools/search_resources.rb+++ b/spree/core/app/tools/spree/agent_tools/search_resources.rb@@ -26,11 +26,12 @@ module Spreeparam :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})"+ param :parent_id, description: PARENT_ID_DESCRIPTION- def call(resource:, filters: nil, sort: nil, limit: nil)+ def call(resource:, filters: nil, sort: nil, limit: nil, parent_id: nil)entry = ResourceMap.find(resource)return unknown_resource(resource) if entry.nil?- return not_searchable(entry) unless entry.dispatchable?+ return not_searchable(entry) if entry.api_path(:index).blank?return forbidden(entry) unless context.permitted?(entry.permission)applied = sanitize_filters(filters)@@ -42,11 +43,10 @@ module Spreeunrecognised = unrecognised_filters(entry, applied)return invalid_filters(entry, unrecognised) if unrecognised.any?- response = dispatch.call(- method: :get,- path: entry.api_path(:index),- params: query_for(applied, sort, limit)- )+ path = entry.path_for(:index, parent_id: parent_id)+ return not_searchable(entry) if path.nil?++ response = dispatch.call(method: :get, path: path, params: query_for(applied, sort, limit))return { error: response.error_message } unless response.success?rows = Array(response.data)diff --git a/spree/core/app/tools/spree/agent_tools/update_resource.rb b/spree/core/app/tools/spree/agent_tools/update_resource.rbindex 61cc2c5b1e..b514e738ef 100644--- a/spree/core/app/tools/spree/agent_tools/update_resource.rb+++ b/spree/core/app/tools/spree/agent_tools/update_resource.rb@@ -14,19 +14,19 @@ module Spreeparam :resource, description: 'Resource key — call describe_resource for the list', required: trueparam :id, description: 'The record id as shown in search results', required: trueparam :attributes, type: :object, description: 'Attributes to change', required: true+ param :parent_id, description: PARENT_ID_DESCRIPTION- def call(resource:, id:, attributes: {})+ def call(resource:, id:, attributes: {}, parent_id: nil)entry, refusal = writable_entry(resource, :update)return refusal if refusalbody, rejection = body_for(entry, attributes)return rejection if rejection- response = dispatch.call(- method: :patch,- path: entry.api_path(:update).sub(':id', id.to_s),- body: body- )+ path, missing = write_path(entry, :update, id: id, parent_id: parent_id)+ return missing if missing++ response = dispatch.call(method: :patch, path: path, body: body)result_for(response, entry, summary: summary(resource: resource, id: id, attributes: attributes))enddiff --git a/spree/core/lib/spree/agent_tool.rb b/spree/core/lib/spree/agent_tool.rbindex aa37fc563d..7957a0a88f 100644--- a/spree/core/lib/spree/agent_tool.rb+++ b/spree/core/lib/spree/agent_tool.rb@@ -21,6 +21,12 @@ module Spree# end# endclass AgentTool+ # The parameter every generic resource tool takes for a resource that+ # lives under another record, such as an order's items.+ PARENT_ID_DESCRIPTION = 'For a resource reached through another record (describe_resource names ' \+ 'it as parent, e.g. an order for its items, discounts and fees): that ' \+ 'record\'s id as shown in search results'.freeze+# 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@@ -178,12 +184,19 @@ class AgentTool# @param action [Symbol] the operation whose path runs under the parent# @return [Hash]def nested_resource_error(entry, verb, action)+ # A top-level path left unfilled is missing its own id, not a parent.+ return { error: "Pass the id of the #{entry.key.singularize.tr('_', ' ')} to use." } unless entry.nested?(action)+parent = entry.parent_key(action)parent_entry = Spree::AgentTools::ResourceMap.find(parent)attribute = parent_entry&.nested_typed_families&.key(entry.model_class)owner = parent.singularize.tr('_', ' ')sentences = ["#{entry.key} belong to #{owner.match?(/\A[aeiou]/) ? 'an' : 'a'} #{owner} and cannot be #{verb} on their own."]+ # Offered only where one parent id fills the path; a resource nested+ # twice has no generic route.+ reachable = entry.path_for(action, id: 'id', parent_id: 'parent').present?+ sentences << "Pass the #{owner}'s id as parent_id to reach them under it." if reachable# Each suggested call is one this caller may actually make; a hint# that leads straight to a permission refusal is worse than none.readable = parent_entry && context.permitted?(parent_entry.permission)diff --git a/spree/core/lib/spree/agent_tools/resource_map.rb b/spree/core/lib/spree/agent_tools/resource_map.rbindex 4d357997f2..6c13c76e6c 100644--- a/spree/core/lib/spree/agent_tools/resource_map.rb+++ b/spree/core/lib/spree/agent_tools/resource_map.rb@@ -100,6 +100,42 @@ module SpreeArray(writable_attributes).map(&:to_s).sortend+ # The record a nested resource is reached through — `order_id` for an+ # order's items, discounts and fees — or nil for a top-level one.+ #+ # @param action [Symbol]+ # @return [String, nil]+ def parent_param(action)+ Array(api_path(action)&.scan(/:([a-z_]+)/)).flatten.reject { |name| name == 'id' }.first+ end++ # The operation's path with its segments filled, or nil when a nested+ # resource was not given the record it lives under.+ #+ # Each value is percent-encoded so it stays one segment: a `?` or `/`+ # in an id would otherwise send the call to a different route than+ # the one the tool checked and the approver was shown. A path with a+ # segment left unfilled — a resource nested two levels deep — is nil+ # too, rather than dispatched with a placeholder in it.+ #+ # @param action [Symbol]+ # @param id [String, nil]+ # @param parent_id [String, nil]+ # @return [String, nil]+ def path_for(action, id: nil, parent_id: nil)+ path = api_path(action)+ return if path.blank?++ path = path.sub(':id', ERB::Util.url_encode(id.to_s)) if id.present?+ parent = parent_param(action)+ if parent+ return if parent_id.blank?++ path = path.sub(":#{parent}", ERB::Util.url_encode(parent_id.to_s))+ end+ path unless path.match?(/:[a-z_]+/)+ end+# The associations the show operation will include when asked, read# from the serializer that renders it.#