Skip to content

armgit / spree

Public Imported from GitHub
0

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

Added a tool for storing a file the merchant provided

Damian Legawiec54280405d918
diff --git a/docs/developer/agentic/admin-mcp.mdx b/docs/developer/agentic/admin-mcp.mdx
index ed274a7fff..76b2f0dc8c 100644
--- a/docs/developer/agentic/admin-mcp.mdx
+++ b/docs/developer/agentic/admin-mcp.mdx
@@ -51,6 +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_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 |
| 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_file_spec.rb b/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rb
new file mode 100644
index 0000000000..47392711af
--- /dev/null
+++ b/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rb
@@ -0,0 +1,94 @@
+require 'spec_helper'
+
+# The dashboard uploads in two steps — presign, then PUT. An agent has only
+# its arguments, so the file arrives base64 and is stored in one call.
+RSpec.describe 'agent file upload' do
+ let(:store) { @default_store }
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+
+ def tool(ctx = context)
+ Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'upload_file' }
+ end
+
+ def upload(filename, bytes, **extra)
+ tool.call(filename: filename, content: Base64.strict_encode64(bytes), **extra)
+ end
+
+ describe 'storing a file' do
+ it 'answers with an id other writes accept' do
+ result = upload('products.csv', "sku,name\nA-1,Thing\n")
+
+ expect(result[:error]).to be_nil
+ expect(result[:content_type]).to eq('text/csv')
+ expect(result[:filename]).to eq('products.csv')
+ expect(result[:file_id]).to be_present
+ end
+
+ # The whole point of the tool: the id has to be the one ActiveStorage
+ # hands a browser, or nothing downstream can use it.
+ it 'produces an id an import attaches and reads back' do
+ csv = "sku,name\nA-1,Thing\n"
+ import = Spree::Imports::Products.new(store: store, user: create(:admin_user))
+
+ import.attachment = upload('products.csv', csv)[:file_id]
+
+ expect(import.save).to be(true)
+ expect(import.reload.attachment.download).to eq(csv)
+ end
+
+ it 'accepts base64 a model wrapped in newlines' do
+ result = tool.call(filename: 'products.csv', content: Base64.encode64("sku,name\nA-1,Thing\n"))
+
+ expect(result[:ok]).to be(true)
+ end
+ end
+
+ describe 'what it refuses' do
+ # `Base64.decode64` cannot be the test — it skips what it does not
+ # recognise, so prose decoded to a few bytes and the refusal talked about
+ # content types instead of encoding.
+ it 'refuses content that is not base64 at all' do
+ expect(tool.call(filename: 'a.csv', content: 'here is the file I mentioned')[:error])
+ .to include('base64')
+ end
+
+ it 'refuses an empty file' do
+ expect(upload('a.csv', '')[:error]).to include('empty')
+ end
+
+ # The type is read from the bytes, so renaming a file does not smuggle it
+ # past — the same reason the attachment validators look at content.
+ it 'refuses a file whose bytes are not a kind it stores' do
+ result = upload('harmless.csv', "<html><script>alert(1)</script></html>")
+
+ expect(result[:error]).to include('text/html')
+ expect(result[:supported_content_types]).to include('text/csv')
+ end
+
+ it 'refuses an executable however it is named' do
+ expect(upload('data.csv', "#!/bin/sh\nrm -rf /\n")[:error]).to include('does not store')
+ end
+
+ it 'refuses a file beyond the cap' do
+ stub_const('Spree::AgentTools::UploadFile::MAX_BYTES', 16)
+
+ expect(upload('big.csv', 'x' * 64)[:error]).to include('must be under')
+ end
+
+ it 'is withheld from a caller who cannot write' do
+ read_only = create(:api_key, :secret, store: store, scopes: ['read_products'])
+
+ expect(tool(Spree::AgentTools::Context.new(store: store, api_key: read_only))).to be_nil
+ end
+ end
+
+ # A stored file is inert until a later write uses it, and that write carries
+ # its own permission — so uploading is not a way to reach anything.
+ describe 'what storing one does not do' do
+ it 'attaches the file to nothing by itself' do
+ expect { upload('products.csv', "sku,name\nA-1,Thing\n") }.
+ not_to change(Spree::Import, :count)
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/upload_file.rb b/spree/core/app/tools/spree/agent_tools/upload_file.rb
new file mode 100644
index 0000000000..5ce1ffb95f
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/upload_file.rb
@@ -0,0 +1,114 @@
+module Spree
+ module AgentTools
+ # Takes a file the merchant handed over and stores it, answering with the
+ # id every other write accepts.
+ #
+ # The dashboard uploads in two steps: ask for a presigned URL, then PUT
+ # the bytes to it. An agent has no second request to make — its arguments
+ # are JSON, so the file arrives as base64 and is stored here in one go.
+ # What comes back is an ordinary ActiveStorage signed id, so nothing
+ # downstream needs to know a model produced it.
+ #
+ # Storing a file is not yet using it: the id is attached by whichever
+ # tool the merchant asked for next, under that tool's own permission.
+ class UploadFile < Spree::AgentTool
+ tool_name 'upload_file'
+ description 'Store a file the merchant provided — a CSV to import, an image for a ' \
+ 'product, a document to attach — and return the id other tools accept. ' \
+ 'Send the bytes base64 encoded. Storing a file does nothing on its own; ' \
+ 'pass the id to the tool that uses it.'
+ # Storing a file changes nothing a merchant can see until the id is
+ # used, so the permission that matters is the one on that write. This
+ # gate is the floor: the same one the dashboard's upload endpoint uses.
+ permission 'write_products'
+ mutating!
+
+ # Base64 is a third larger than the bytes it carries, and the whole
+ # argument passes through the model's context on its way here. Beyond
+ # this a file belongs in the dashboard's uploader.
+ MAX_BYTES = 10.megabytes
+
+ # What a merchant plausibly hands an agent. Deliberately not "anything":
+ # a stored blob is attached later by a tool that may not check, and the
+ # formats below are the ones the attachments themselves accept.
+ PERMITTED_CONTENT_TYPES = %w[
+ text/csv
+ application/pdf
+ image/jpeg
+ image/png
+ image/webp
+ image/heic
+ image/gif
+ application/zip
+ application/msword
+ application/vnd.openxmlformats-officedocument.wordprocessingml.document
+ application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
+ ].freeze
+
+ param :filename, description: 'The file name, with its extension', required: true
+ param :content, description: 'The file bytes, base64 encoded', required: true
+ param :content_type, description: "The file's media type, e.g. text/csv or application/pdf"
+
+ def call(filename:, content:, content_type: nil)
+ bytes = decode(content)
+ return { error: 'content must be base64 encoded.' } if bytes.nil?
+ return { error: 'The file is empty.' } if bytes.empty?
+ return too_large(bytes) if bytes.bytesize > MAX_BYTES
+
+ # Read from the bytes rather than trusting what the caller named it:
+ # a model repeating a filename it was told is the same weak evidence
+ # as an uploader's own header, which is why the attachment validators
+ # look at content too.
+ declared = content_type.presence || Marcel::MimeType.for(StringIO.new(bytes), name: filename)
+ return unsupported(declared) unless PERMITTED_CONTENT_TYPES.include?(declared)
+
+ blob = ActiveStorage::Blob.create_and_upload!(
+ io: StringIO.new(bytes),
+ filename: filename,
+ content_type: declared,
+ service_name: Spree.private_storage_service_name
+ )
+
+ {
+ ok: true,
+ file_id: blob.signed_id,
+ filename: blob.filename.to_s,
+ content_type: blob.content_type,
+ byte_size: blob.byte_size
+ }
+ end
+
+ def summary(arguments)
+ "Store the file #{arguments[:filename]}"
+ end
+
+ private
+
+ # A model that wrapped the payload in newlines is forgiven; one that
+ # sent something else entirely is not. `decode64` cannot be used as the
+ # test: it skips whatever it does not recognise, so a sentence of prose
+ # decodes to a handful of bytes and the refusal that followed talked
+ # about content types rather than about encoding.
+ def decode(content)
+ Base64.strict_decode64(content.to_s.gsub(/\s+/, ''))
+ rescue ArgumentError
+ nil
+ end
+
+ def too_large(bytes)
+ {
+ error: "That file is #{ActiveSupport::NumberHelper.number_to_human_size(bytes.bytesize)}. " \
+ "Files this tool stores must be under #{ActiveSupport::NumberHelper.number_to_human_size(MAX_BYTES)} — " \
+ 'upload a larger one from the dashboard.'
+ }
+ end
+
+ def unsupported(content_type)
+ {
+ error: "This tool does not store #{content_type.inspect} files.",
+ supported_content_types: PERMITTED_CONTENT_TYPES
+ }
+ 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 277f56370a..87366ff4b6 100644
--- a/spree/core/lib/spree/agent_tools/default_catalog.rb
+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb
@@ -20,6 +20,7 @@ module Spree
Spree::AgentTools::UpdateResource
Spree::AgentTools::DeleteResource
Spree::AgentTools::CurateProducts
+ Spree::AgentTools::UploadFile
Spree::AgentTools::QueryReport
Spree::AgentTools::DescribeReporting
Spree::AgentTools::CreateExport
@@ -150,7 +151,9 @@ module Spree
'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.',
+ 'Reads the uploaded file and proposes its column mapping. Runs as part of creating ' \
+ 'an import rather than on its own — a mapping proposal against a file nobody has ' \
+ 'attached yet means nothing.',
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.',
diff --git a/spree/mcp/lib/spree/mcp/server.rb b/spree/mcp/lib/spree/mcp/server.rb
index 48a3a932e4..cbf8fecbc8 100644
--- a/spree/mcp/lib/spree/mcp/server.rb
+++ b/spree/mcp/lib/spree/mcp/server.rb
@@ -30,6 +30,10 @@ module Spree
search results. You are only offered the tools this credential permits,
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.
+
Files are MCP resources, not tool results. A finished export is one:
after create_export, read its contents from resources rather than
reporting a download path — the path is for the merchant, the