Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added tools for putting an uploaded file on a product or into an import

Damian Legawiec862e28156bf4
diff --git a/docs/developer/agentic/admin-mcp.mdx b/docs/developer/agentic/admin-mcp.mdx
index 3568173026..7ed3fb29ce 100644
--- a/docs/developer/agentic/admin-mcp.mdx
+++ b/docs/developer/agentic/admin-mcp.mdx
@@ -51,7 +51,7 @@ The tools are not a mirror of the API's endpoints — there would be hundreds, a
| 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_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 |
+| Receiving files | `upload_file`, then `media_create` or `create_import` | A merchant hands over images or a CSV: store the file, then put it in a product gallery or start an import from it |
| Reading files | MCP resources | Finished exports, and documents attached to records — a buyer's purchase order, a shipping label |
| Store setup | `create_resource`, `update_resource`, `delete_resource` | Markets, channels, delivery and payment methods, tax rates and the rest of the settings screens |
diff --git a/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb b/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb
new file mode 100644
index 0000000000..b954f5f2bb
--- /dev/null
+++ b/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb
@@ -0,0 +1,122 @@
+require 'spec_helper'
+
+# A file the merchant hands over has to reach something. upload_file stores
+# it; these are the tools that use the id it returns.
+RSpec.describe 'agent tools that consume an upload' do
+ let(:store) { @default_store }
+ let(:admin) { create(:admin_user) }
+ let(:context) do
+ Spree::AgentTools::Context.new(store: store, user: admin,
+ granted_scopes: %w[write_products read_products write_media write_customers])
+ end
+
+ def tool(name, ctx = context)
+ Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == name }
+ end
+
+ def upload(filename, bytes, ctx = context)
+ tool('upload_file', ctx).call(filename: filename, content: Base64.strict_encode64(bytes))[:file_id]
+ end
+
+ # One transparent pixel. A real PNG, because the type is read from bytes.
+ def png
+ Base64.decode64('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8AAAwAB/AF+AaTqAAAAAElFTkSuQmCC')
+ end
+
+ describe 'media_create' do
+ let(:product) { create(:product, store: store) }
+
+ it 'places an uploaded file in a product gallery' do
+ result = tool('media_create').call(file_id: upload('shot.png', png),
+ product_id: product.prefixed_id, alt: 'Studio shot')
+
+ expect(result[:error]).to be_nil
+ expect(result[:media_type]).to eq('image')
+
+ media = Spree::Media.find_by_prefix_id(result[:id])
+ expect(media.viewable).to eq(product)
+ expect(media.alt).to eq('Studio shot')
+ end
+
+ # A row with no owner is a library file: uploaded, not yet placed.
+ it 'leaves it unplaced when no product is named' do
+ result = tool('media_create').call(file_id: upload('lib.png', png))
+
+ expect(result[:error]).to be_nil
+ expect(Spree::Media.find_by_prefix_id(result[:id]).viewable).to be_nil
+ end
+
+ it 'refuses a file id this store did not upload' do
+ expect(tool('media_create').call(file_id: 'not-a-signed-id')[:error]).to include('upload_file')
+ end
+
+ it 'refuses a product in another store' do
+ theirs = create(:product, store: create(:store, code: "other-#{SecureRandom.hex(4)}"))
+
+ expect(tool('media_create').call(file_id: upload('x.png', png), product_id: theirs.prefixed_id)[:error]).
+ to include('No product found')
+ end
+
+ it 'is withheld from a caller who cannot write media' do
+ no_media = Spree::AgentTools::Context.new(store: store, user: admin, granted_scopes: ['read_media'])
+
+ expect(tool('media_create', no_media)).to be_nil
+ end
+ end
+
+ describe 'create_import' do
+ let(:csv) { "sku,name,price\nIMP-1,Imported,24.99\n" }
+
+ # Reading the header row and proposing a mapping is the safe half of the
+ # wizard: the merchant sees what the columns were taken to mean before any
+ # row is written.
+ it 'starts an import and proposes its mapping' do
+ result = tool('create_import').call(resource: 'products', file_id: upload('products.csv', csv))
+
+ expect(result[:error]).to be_nil
+ expect(result[:status]).to eq('mapping')
+
+ import = Spree::Import.find_by_prefix_id(result[:id])
+ expect(import.csv_headers).to eq(%w[sku name price])
+ expect(import.mappings).to be_present
+ end
+
+ it 'writes no records until the mapping is confirmed' do
+ expect { tool('create_import').call(resource: 'products', file_id: upload('products.csv', csv)) }.
+ not_to change(Spree::Product, :count)
+ end
+
+ # The permission is the write scope of what is being imported, computed
+ # per call — a class-level key could not say that, which is why the
+ # resource reached the map read-only.
+ it 'refuses a kind the grant does not cover' do
+ file = upload('products.csv', csv)
+ narrowed = Spree::AgentTools::Context.new(store: store, user: admin,
+ granted_scopes: %w[write_customers write_products])
+
+ # write_products is held, so the tool is offered; write_customers alone
+ # is what a customers import would need, and products is refused for a
+ # grant that carries neither.
+ only_customers = Spree::AgentTools::Context.new(store: store, user: admin,
+ granted_scopes: ['write_customers'])
+
+ expect(tool('create_import', narrowed).call(resource: 'products', file_id: file)[:ok]).to be(true)
+ expect(tool('create_import', only_customers).call(resource: 'products', file_id: file)[:error]).
+ to include('permission to import products')
+ end
+
+ it 'names the kinds it can import when given one it cannot' do
+ result = tool('create_import').call(resource: 'widgets', file_id: upload('products.csv', csv))
+
+ expect(result[:error]).to include('widgets')
+ expect(result[:available]).to include('products', 'customers')
+ end
+
+ it 'says so when the file is not CSV at all' do
+ result = tool('create_import').call(resource: 'products', file_id: upload('shot.png', png))
+
+ expect(result[:error]).to be_present
+ expect(result[:ok]).to be_nil
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/create_import.rb b/spree/core/app/tools/spree/agent_tools/create_import.rb
new file mode 100644
index 0000000000..259ce422a4
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/create_import.rb
@@ -0,0 +1,117 @@
+module Spree
+ module AgentTools
+ # Starts a CSV import from a file the merchant provided.
+ #
+ # Gated on the WRITE scope of what is being imported, computed per call —
+ # a customers import needs `write_customers`, a products import
+ # `write_products`. A single class-level key could not say that, which is
+ # why the resource reached the map read-only; `create_export` answers the
+ # same question the same way.
+ #
+ # Creating the import reads the file's header row and proposes a column
+ # mapping. Nothing is written to the catalog until that mapping is
+ # confirmed, so this is the safe half of the wizard: the merchant still
+ # sees what the columns were taken to mean before any row lands.
+ class CreateImport < Spree::AgentTool
+ tool_name 'create_import'
+ description 'Start a CSV import from a file the merchant provided. Call upload_file ' \
+ 'first and pass the file_id it returns. The columns are read and a mapping ' \
+ 'proposed; no records change until the mapping is confirmed.'
+ # Per-resource, answered in `call` — a class-level key would hide the
+ # tool from a caller who may import one kind of record but not another.
+ permission nil
+ mutating!
+
+ param :resource, description: 'What the file holds: products, customers, purchase_orders',
+ required: true
+ param :file_id, description: 'The file_id upload_file returned', required: true
+
+ def call(resource:, file_id:)
+ import_class = import_class_for(resource)
+ return unknown_resource(resource) if import_class.nil?
+
+ required = "write_#{import_class.required_scope}"
+ unless context.holds?(required)
+ return { error: "You do not have permission to import #{resource.to_s.tr('_', ' ')}." }
+ end
+
+ start(import_class, resource, file_id)
+ end
+
+ def summary(arguments)
+ "Start a #{arguments[:resource].to_s.tr('_', ' ')} import"
+ end
+
+ private
+
+ def start(import_class, resource, file_id)
+ owner = importing_user
+ return { error: no_user_error } if owner.nil?
+
+ import = import_class.new(store: context.store, user: owner)
+ import.attachment = file_id
+
+ refusal = unauthorized(:create, import)
+ return refusal if refusal
+ return { error: import.errors.full_messages.to_sentence } unless import.save
+
+ mapping = Spree.import_start_mapping_workflow.call(import: import)
+ return { error: mapping_failure(mapping, import) } unless mapping.success?
+
+ {
+ ok: true,
+ id: import.prefixed_id,
+ resource: resource.to_s,
+ status: import.reload.status,
+ # The mapping is the point of this step: the model should read it
+ # back and tell the merchant what the columns were taken to mean
+ # before anything is written.
+ next_step: "Call describe_import_mapping with id #{import.prefixed_id} to see the " \
+ 'columns, then confirm it to run the import.',
+ dashboard_path: ResourceMap.find('imports')&.dashboard_path_for(import)
+ }
+ rescue ::CSV::MalformedCSVError, EncodingError => e
+ { error: "That file could not be read as CSV: #{e.message}" }
+ rescue ActiveSupport::MessageVerifier::InvalidSignature, ActiveRecord::RecordNotFound
+ { error: "#{file_id.inspect} is not a file this store uploaded. Call upload_file first." }
+ rescue ActiveStorage::FileNotFoundError
+ { error: 'That upload did not finish — its bytes are missing. Upload the file again.' }
+ end
+
+ def mapping_failure(result, import)
+ error = result.error
+ message = error.try(:value).is_a?(String) ? error.value : error.to_s
+
+ message.presence || import.processing_errors.presence || 'The file could not be mapped.'
+ end
+
+ # An import belongs to a person — it emails them when it finishes and
+ # its failed rows are theirs to retry. A grant carries the admin who
+ # approved it; a standing key carries whoever minted it, which is the
+ # same fallback the Admin API uses.
+ def importing_user
+ return context.user if context.user.present?
+
+ creator = context.api_key&.created_by
+ creator if creator.is_a?(Spree.admin_user_class)
+ end
+
+ def no_user_error
+ 'An import has to belong to a staff member, and this credential names none. ' \
+ 'Connect an agent through the dashboard, or start the import there.'
+ end
+
+ def import_class_for(resource)
+ key = resource.to_s.downcase
+ Spree::Import.available_types.find { |klass| klass.name.demodulize.underscore == key }
+ end
+
+ def unknown_resource(resource)
+ {
+ error: "Cannot import #{resource.inspect}.",
+ available: Spree::Import.available_types.map { |k| k.name.demodulize.underscore }.sort
+ }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/create_media.rb b/spree/core/app/tools/spree/agent_tools/create_media.rb
new file mode 100644
index 0000000000..21487f906b
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/create_media.rb
@@ -0,0 +1,80 @@
+module Spree
+ module AgentTools
+ # Puts a file into the media library, optionally on a product.
+ #
+ # Creating media needs a file, which an agent had no way to supply until
+ # `upload_file` existed — which is why the resource reached the map
+ # read-only. The id that tool returns is what this one takes.
+ #
+ # A row with no owner is a library file: uploaded, not yet placed. Naming
+ # a product places it in that product's gallery, which is what a merchant
+ # handing over photographs usually means.
+ class CreateMedia < Spree::AgentTool
+ tool_name 'media_create'
+ description 'Add an uploaded file to the media library, or straight onto a product. ' \
+ 'Call upload_file first and pass the file_id it returns. Without a product ' \
+ 'the file sits in the library for the merchant to place later.'
+ permission 'write_media'
+ mutating!
+
+ param :file_id, description: 'The file_id upload_file returned', required: true
+ param :product_id, description: "A product's prefixed id, to place the file in its gallery"
+ param :alt, description: 'Alt text describing the image, for accessibility and SEO'
+
+ def call(file_id:, product_id: nil, alt: nil)
+ product = nil
+ if product_id.present?
+ product = find_product(product_id)
+ return { error: "No product found for #{product_id.inspect}." } if product.nil?
+
+ refusal = unauthorized(:update, product)
+ return refusal if refusal
+ end
+
+ build_and_save(file_id: file_id, product: product, alt: alt)
+ end
+
+ def summary(arguments)
+ return "Add a file to #{arguments[:product_id]}'s gallery" if arguments[:product_id].present?
+
+ 'Add a file to the media library'
+ end
+
+ private
+
+ def build_and_save(file_id:, product:, alt:)
+ media = Spree::Media.new(store: context.store, alt: alt.presence)
+ media.viewable = product if product
+
+ # The signed id is verified by ActiveStorage itself: one that was not
+ # issued by this installation does not resolve, so a model cannot
+ # invent a reference to someone else's file.
+ media.attachment = file_id
+
+ return { error: media.errors.full_messages.to_sentence.presence || 'The file could not be added.' } unless
+ media.save
+
+ {
+ ok: true,
+ id: media.prefixed_id,
+ filename: media.attachment.filename.to_s,
+ media_type: media.media_type,
+ product_id: product&.prefixed_id,
+ # The media library has no page of its own in the map, so the link
+ # that helps is the product's — where the merchant will look at it.
+ dashboard_path: product && ResourceMap.find('products')&.dashboard_path_for(product)
+ }.compact
+ rescue ActiveSupport::MessageVerifier::InvalidSignature, ActiveRecord::RecordNotFound
+ { error: "#{file_id.inspect} is not a file this store uploaded. Call upload_file first." }
+ rescue ActiveStorage::FileNotFoundError
+ { error: 'That upload did not finish — its bytes are missing. Upload the file again.' }
+ end
+
+ def find_product(id)
+ context.accessible(Spree::Product.for_store(context.store), :update).find_by_prefix_id(id)
+ rescue StandardError
+ nil
+ 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
index 36ac795fd0..5c3467a2f3 100644
--- a/spree/core/lib/spree/agent_tools/default_catalog.rb
+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb
@@ -22,6 +22,8 @@ module Spree
Spree::AgentTools::CurateProducts
Spree::AgentTools::UploadFile
Spree::AgentTools::CreateOrder
+ Spree::AgentTools::CreateMedia
+ Spree::AgentTools::CreateImport
Spree::AgentTools::QueryReport
Spree::AgentTools::DescribeReporting
Spree::AgentTools::CreateExport
diff --git a/spree/mcp/lib/spree/mcp/server.rb b/spree/mcp/lib/spree/mcp/server.rb
index cbf8fecbc8..cd8ba90edf 100644
--- a/spree/mcp/lib/spree/mcp/server.rb
+++ b/spree/mcp/lib/spree/mcp/server.rb
@@ -31,8 +31,9 @@ module Spree
so a tool you cannot see is one this store has not granted.
A file the merchant gives you goes the other way: upload_file stores it
- and answers with an id, which you then pass to whatever uses it.
- Storing one changes nothing by itself.
+ and answers with an id, which you then pass to whatever uses it —
+ media_create to put an image on a product, create_import to start a
+ CSV import. Storing one changes nothing by itself.
Files are MCP resources, not tool results. A finished export is one:
after create_export, read its contents from resources rather than