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
Added a tool for starting a draft order
Damian Legawiece5df0f83f2c3
diff --git a/docs/developer/agentic/admin-mcp.mdx b/docs/developer/agentic/admin-mcp.mdxindex 76b2f0dc8c..3568173026 100644--- a/docs/developer/agentic/admin-mcp.mdx+++ b/docs/developer/agentic/admin-mcp.mdx@@ -49,7 +49,7 @@ The tools are not a mirror of the API's endpoints — there would be hundreds, a| --- | --- | --- || Finding things | `describe_resource`, `search_resources`, `get_resource` | Discovering which resources exist and what they can be filtered by, then finding and reading records || Answering with numbers | `describe_reporting`, `query_report` | Revenue, orders and units, sliced by time, product, channel or country — the same figures the dashboard charts show |-| Doing things | One tool per operation: `orders_cancel`, `fulfillments_mark_delivered`, `products_activate`, `refunds_create`, `price_lists_activate` and around fifty more | Each runs the same workflow the dashboard runs, so validations, emails and webhooks behave identically |+| Doing things | One tool per operation: `orders_create`, `orders_cancel`, `fulfillments_mark_delivered`, `products_activate`, `refunds_create`, `price_lists_activate` and around fifty more | Each runs the same workflow the dashboard runs, so validations, emails and webhooks behave identically || Merchandising | `curate_products` | Which products a category, collection, catalog or price list holds || Receiving files | `upload_file` | Storing a CSV, image or document the merchant provided, for another tool to use || Reading files | MCP resources | Finished exports, and documents attached to records — a buyer's purchase order, a shipping label |diff --git a/spree/api/spec/tools/spree/agent_tools/create_order_spec.rb b/spree/api/spec/tools/spree/agent_tools/create_order_spec.rbnew file mode 100644index 0000000000..9243efc028--- /dev/null+++ b/spree/api/spec/tools/spree/agent_tools/create_order_spec.rb@@ -0,0 +1,115 @@+require 'spec_helper'++# Cancelling and completing an order reach an agent through the workflow+# allowlist. Creating one is a service, so it is a written tool — and the gap+# showed up in use: an agent could make the customer but not the order.+RSpec.describe 'agent draft order creation' do+ let(:store) { @default_store }+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }+ let(:product) { create(:product, store: store, status: 'active') }+ let(:variant) { product.variants.first || create(:variant, product: product) }++ def tool(ctx = context)+ Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'orders_create' }+ end++ describe 'creating one' do+ it 'leaves a draft for the merchant to review' do+ result = tool.call(email: '[email protected]',+ items: [{ variant_id: variant.prefixed_id, quantity: 3 }])++ expect(result[:error]).to be_nil+ expect(result[:status]).to eq('draft')+ expect(result[:item_count]).to eq(3)++ order = store.orders.find_by_prefix_id(result[:id])+ expect(order.line_items.sum(&:quantity)).to eq(3)+ expect(order.email).to eq('[email protected]')+ end++ it 'orders for an existing customer' do+ customer = create(:customer)++ result = tool.call(customer_id: customer.prefixed_id,+ items: [{ variant_id: variant.prefixed_id, quantity: 1 }])++ expect(result[:error]).to be_nil+ expect(store.orders.find_by_prefix_id(result[:id]).customer).to eq(customer)+ end++ # Who asked matters later, on the order's own record.+ it 'records the credential that asked as the creator' do+ result = tool.call(email: '[email protected]', items: [{ variant_id: variant.prefixed_id }])++ expect(store.orders.find_by_prefix_id(result[:id]).created_by).to eq(api_key)+ end++ it 'defaults a line with no quantity to one' do+ result = tool.call(email: '[email protected]', items: [{ variant_id: variant.prefixed_id }])++ expect(result[:item_count]).to eq(1)+ end+ end++ # The mistake a model makes most: a product has variants, and only a variant+ # can be ordered. Answering with the choices is what lets it correct itself+ # in one step instead of asking the merchant.+ describe 'given a product where a variant belongs' do+ it 'names the variants to choose between' do+ create(:variant, product: product)++ result = tool.call(email: '[email protected]', items: [{ variant_id: product.prefixed_id }])++ expect(result[:error]).to include('is a product')+ expect(result[:variants].map { |v| v[:id] }).to match_array(product.variants.map(&:prefixed_id))+ end+ end++ describe 'refusals' do+ it 'needs someone to order for' do+ expect(tool.call(items: [{ variant_id: variant.prefixed_id }])[:error]).to include('customer_id or an email')+ end++ it 'needs at least one item' do+ expect(tool.call(email: '[email protected]', items: [])[:error]).to include('at least one item')+ end++ it 'needs a variant on every line' do+ expect(tool.call(email: '[email protected]', items: [{ quantity: 2 }])[:error]).to include('needs a variant_id')+ end++ it 'refuses an unknown customer' do+ expect(tool.call(customer_id: 'cust_nope', items: [{ variant_id: variant.prefixed_id }])[:error]).+ to include('No customer found')+ end++ # Another store's variant is not orderable here, so it is not found rather+ # than quietly ordered.+ it 'cannot order a variant belonging to another store' do+ theirs = create(:product, store: create(:store, code: "other-#{SecureRandom.hex(4)}"), status: 'active')++ result = tool.call(email: '[email protected]', items: [{ variant_id: theirs.variants.first.prefixed_id }])++ expect(result[:error]).to include('No variant found')+ expect(store.orders.where(email: '[email protected]')).to be_empty+ end++ it 'is withheld from a caller who may only read orders' do+ read_only = create(:api_key, :secret, store: store, scopes: ['read_orders'])++ expect(tool(Spree::AgentTools::Context.new(store: store, api_key: read_only))).to be_nil+ end++ # The service's own refusal, in its words — a draft product cannot be sold,+ # and the merchant needs to know which rule stopped it.+ it 'passes on why the order could not be created' do+ draft = create(:product, store: store, status: 'draft')++ result = tool.call(email: '[email protected]', items: [{ variant_id: draft.variants.first.prefixed_id }])++ expect(result[:error]).to be_present+ expect(result[:ok]).to be_nil+ end+ end+enddiff --git a/spree/core/app/tools/spree/agent_tools/create_order.rb b/spree/core/app/tools/spree/agent_tools/create_order.rbnew file mode 100644index 0000000000..5b65c2e407--- /dev/null+++ b/spree/core/app/tools/spree/agent_tools/create_order.rb@@ -0,0 +1,139 @@+module Spree+ module AgentTools+ # Starts a draft order for a customer, with the lines it should hold.+ #+ # Cancelling and completing an order are workflows, so they reach an agent+ # through the workflow allowlist. Creating one is a service — the admin+ # create takes customer, items, addresses and a coupon in a single call —+ # so it is written out here rather than derived.+ #+ # A draft, never a placed order: the merchant reviews it, and completing+ # it is `orders_complete`, its own decision with its own approval.+ class CreateOrder < Spree::AgentTool+ tool_name 'orders_create'+ description 'Start a draft order for a customer, with the items it should hold. ' \+ 'Items name a variant, not a product — search variants to pick one when ' \+ 'a product has several. The order is left as a draft for the merchant to ' \+ 'review; completing it is a separate step.'+ permission 'write_orders'+ mutating!++ param :customer_id, description: "The customer's prefixed id. Either this or email is required."+ param :email, description: 'Email of the person ordering, when they are not an existing customer'+ param :items, type: :array, items: :object, required: true,+ description: 'Lines to order: [{"variant_id": "variant_k5nR8xLq", "quantity": 3}]'+ param :currency, description: "Three-letter code; the store's own currency when omitted"+ param :customer_note, description: 'A note the merchant wants kept on the order'++ def call(items:, customer_id: nil, email: nil, currency: nil, customer_note: nil)+ return { error: 'Give either a customer_id or an email.' } if customer_id.blank? && email.blank?++ customer = nil+ if customer_id.present?+ customer = find_customer(customer_id)+ return { error: "No customer found for #{customer_id.inspect}." } if customer.nil?+ end++ lines, refusal = resolve_items(items)+ return refusal if refusal++ create(customer: customer, email: email, lines: lines, currency: currency, note: customer_note)+ end++ def summary(arguments)+ count = Array(arguments[:items]).sum { |item| (item[:quantity] || item['quantity'] || 1).to_i }+ who = arguments[:email].presence || arguments[:customer_id]++ "Create a draft order for #{who} with #{count} #{'item'.pluralize(count)}"+ end++ private++ def create(customer:, email:, lines:, currency:, note:)+ result = Spree.order_create_service.call(+ store: context.store,+ customer: customer,+ created_by: context.principal,+ params: {+ email: email.presence || customer&.email,+ currency: currency.presence,+ customer_note: note.presence,+ items: lines+ }.compact+ )++ return { error: failure_message(result) } unless result.success?++ order = result.value+ {+ ok: true,+ id: order.prefixed_id,+ number: order.number,+ status: order.status,+ item_count: order.line_items.sum(&:quantity),+ total: order.display_total.to_s,+ dashboard_path: ResourceMap.find('orders')&.dashboard_path_for(order)+ }+ end++ # A product has variants, and only a variant can be ordered. Naming the+ # product instead is the mistake a model makes most here, so it is+ # answered with the variants to choose between rather than a refusal+ # the model cannot act on.+ def resolve_items(items)+ rows = Array(items).map { |item| item.respond_to?(:to_h) ? item.to_h.symbolize_keys : {} }+ return [nil, { error: 'Give at least one item.' }] if rows.empty?++ resolved = rows.map do |row|+ id = row[:variant_id].presence+ return [nil, { error: 'Every item needs a variant_id.' }] if id.blank?++ variant = find_variant(id)+ return [nil, variant_refusal(id)] if variant.nil?++ { variant_id: variant.id, quantity: [(row[:quantity] || 1).to_i, 1].max }+ end++ [resolved, nil]+ end++ def find_customer(id)+ context.accessible(Spree.customer_class.for_store(context.store), :show).find_by_prefix_id(id)+ rescue StandardError+ nil+ end++ def find_variant(id)+ context.accessible(Spree::Variant.for_store(context.store), :show).find_by_prefix_id(id)+ rescue StandardError+ nil+ end++ # Where the id names a product, list its variants: that is the one extra+ # step the model needs, and it already has permission to read them.+ def variant_refusal(id)+ product = begin+ context.accessible(Spree::Product.for_store(context.store), :show).find_by_prefix_id(id)+ rescue StandardError+ nil+ end+ return { error: "No variant found for #{id.inspect}." } if product.nil?++ {+ error: "#{id.inspect} is a product, and an order holds variants. " \+ "#{product.name} has #{product.variants.count} to choose from.",+ variants: product.variants.map do |variant|+ { id: variant.prefixed_id, label: variant.options_text.presence || variant.sku }+ end+ }+ end++ def failure_message(result)+ error = result.error+ message = error.try(:value).is_a?(String) ? error.value : error.to_s++ message.presence || 'The order could not be created.'+ end+ end+ end+enddiff --git a/spree/core/lib/spree/agent_tools/default_catalog.rb b/spree/core/lib/spree/agent_tools/default_catalog.rbindex 87366ff4b6..36ac795fd0 100644--- a/spree/core/lib/spree/agent_tools/default_catalog.rb+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb@@ -21,6 +21,7 @@ module SpreeSpree::AgentTools::DeleteResourceSpree::AgentTools::CurateProductsSpree::AgentTools::UploadFile+ Spree::AgentTools::CreateOrderSpree::AgentTools::QueryReportSpree::AgentTools::DescribeReportingSpree::AgentTools::CreateExport