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 the files attached to records as MCP resources

Damian Legawiec2bd83d3b0a60
diff --git a/docs/developer/agentic/admin-mcp.mdx b/docs/developer/agentic/admin-mcp.mdx
index e8590c8eba..ed274a7fff 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 |
+| 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 |
An agent is only ever shown the tools its key permits, so the list stays small and relevant: a key minted for order operations sees around twenty.
diff --git a/spree/core/lib/spree/agent_tools.rb b/spree/core/lib/spree/agent_tools.rb
index fe1bad5fce..130e16c30b 100644
--- a/spree/core/lib/spree/agent_tools.rb
+++ b/spree/core/lib/spree/agent_tools.rb
@@ -1,6 +1,7 @@
require 'spree/agent_tools/registry'
require 'spree/agent_tools/context'
require 'spree/agent_tools/resource_map'
+require 'spree/agent_tools/attachment_registry'
require 'spree/agent_tools/membership_map'
require 'spree/agent_tools/record_summary'
require 'spree/agent_tools/workflow_schema'
diff --git a/spree/core/lib/spree/agent_tools/attachment_registry.rb b/spree/core/lib/spree/agent_tools/attachment_registry.rb
new file mode 100644
index 0000000000..048df6e9e1
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/attachment_registry.rb
@@ -0,0 +1,86 @@
+module Spree
+ module AgentTools
+ # Which files on a record an agent may read, reached as
+ # {Spree.agent_attachments}. An extension adds its own the same way it
+ # registers a tool:
+ #
+ # Spree.agent_attachments.register(
+ # resource: 'supplier_contracts', attachment: :document, label: 'Contract'
+ # )
+ #
+ # An allowlist, not a sweep of every `has_one_attached`: a subject access
+ # export is one customer's entire personal data, and a digital asset is
+ # the product someone paid for. Neither belongs in a model's context
+ # window, and a model that grows an attachment later stays withheld until
+ # somebody decides otherwise — so nothing is readable until registered.
+ #
+ # Permission, tenancy and record-level filtering are not repeated here:
+ # the resource's {ResourceMap} entry already carries them, derived from
+ # the controller that serves it. A file costs what its record costs.
+ class AttachmentRegistry
+ include Enumerable
+
+ Entry = Struct.new(:resource, :attachment, :label, keyword_init: true) do
+ # The map entry owning this resource's permission and scoping.
+ #
+ # @return [ResourceMap::Entry, nil]
+ def resource_entry
+ ResourceMap.find(resource)
+ end
+
+ # Records of this kind carrying this file that the caller may read.
+ #
+ # @param context [Spree::AgentTools::Context]
+ # @return [ActiveRecord::Relation, Array]
+ def scope_for(context)
+ return [] unless readable_by?(context)
+
+ resource_entry.scope_for(context).joins(:"#{attachment}_attachment")
+ end
+
+ # @param context [Spree::AgentTools::Context]
+ # @return [Boolean]
+ def readable_by?(context)
+ entry = resource_entry
+ entry.present? && context.permitted?(entry.permission)
+ end
+
+ # @param record [ActiveRecord::Base]
+ # @return [ActiveStorage::Attached::One, nil]
+ def attached(record)
+ file = record.public_send(attachment)
+ file if file.respond_to?(:attached?) && file.attached?
+ end
+ end
+
+ def initialize
+ @entries = {}
+ end
+
+ def each(&block)
+ @entries.values.each(&block)
+ end
+
+ # @param resource [String, Symbol] the ResourceMap key owning the file
+ # @param attachment [Symbol] the ActiveStorage attachment name
+ # @param label [String] what a merchant calls it
+ # @return [Entry]
+ def register(resource:, attachment:, label:)
+ @entries[resource.to_s] = Entry.new(resource: resource.to_s,
+ attachment: attachment.to_sym,
+ label: label)
+ end
+
+ # @param resource [String, Symbol]
+ # @return [Entry, nil]
+ def find(resource)
+ @entries[resource.to_s]
+ end
+
+ # @return [void]
+ def reset!
+ @entries = {}
+ 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 3e087e4700..277f56370a 100644
--- a/spree/core/lib/spree/agent_tools/default_catalog.rb
+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb
@@ -28,6 +28,25 @@ module Spree
Spree::AgentTools::ProposeImportMapping
].freeze
+ # Files a client may fetch, as `{resource, attachment, label}`.
+ #
+ # Each rides the permission of the record carrying it, so a file never
+ # becomes a way around a scope the merchant withheld. Deliberately not
+ # every attachment in the schema:
+ #
+ # - `data_requests.export_file` is a subject access export — one
+ # customer's entire personal data, assembled because they asked for
+ # it. It is theirs, not training material.
+ # - `digital_assets.attachment` is the product a customer paid for.
+ # - Logos, avatars and category imagery say nothing a model needs, and
+ # their URLs are already public.
+ ATTACHMENTS = [
+ { resource: 'orders', attachment: :po_document, label: 'Purchase order' },
+ { resource: 'shipping_labels', attachment: :file, label: 'Shipping label' },
+ { resource: 'media', attachment: :attachment, label: 'Media file' },
+ { resource: 'imports', attachment: :attachment, label: 'Import file' }
+ ].freeze
+
# Workflow key => permission, or => {permission:, except:, summary:}.
WORKFLOWS = {
# Catalog
@@ -142,9 +161,10 @@ module Spree
class << self
# @param registry [Spree::AgentTools::Registry]
# @return [void]
- def install(registry)
+ def install(registry, attachments = nil)
TOOLS.each { |tool| registry << tool }
registry.expose_workflows(**WORKFLOWS)
+ ATTACHMENTS.each { |attributes| attachments.register(**attributes) } if attachments
end
end
end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 12f3036dbb..c06da59ae1 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -523,6 +523,7 @@ module Spree
#
# @return [Spree::AgentTools::Registry]
singleton_class.delegate :agent_tools, :agent_tools=, to: :spree_config
+ singleton_class.delegate :agent_attachments, :agent_attachments=, 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);
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index f468378363..3f2aa6470d 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -44,6 +44,7 @@ module Spree
:custom_fields,
:reporting,
:agent_tools,
+ :agent_attachments,
:integrations,
:number_generators,
:subscribers,
@@ -164,7 +165,9 @@ module Spree
# 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)
+ app.config.spree.agent_attachments = Spree::AgentTools::AttachmentRegistry.new
+ Spree::AgentTools::DefaultCatalog.install(app.config.spree.agent_tools,
+ app.config.spree.agent_attachments)
end
diff --git a/spree/core/spec/lib/spree/agent_tools/attachment_registry_spec.rb b/spree/core/spec/lib/spree/agent_tools/attachment_registry_spec.rb
new file mode 100644
index 0000000000..c912717f9e
--- /dev/null
+++ b/spree/core/spec/lib/spree/agent_tools/attachment_registry_spec.rb
@@ -0,0 +1,35 @@
+require 'spec_helper'
+
+RSpec.describe Spree::AgentTools::AttachmentRegistry do
+ subject(:registry) { described_class.new }
+
+ describe 'what an extension can add' do
+ it 'registers a file against the resource that owns it' do
+ registry.register(resource: 'orders', attachment: :po_document, label: 'Purchase order')
+ entry = registry.find('orders')
+
+ expect(entry.attachment).to eq(:po_document)
+ expect(entry.label).to eq('Purchase order')
+ end
+
+ it 'answers nothing for a resource nobody registered' do
+ expect(registry.find('data_requests')).to be_nil
+ end
+ end
+
+ describe 'what core ships' do
+ # Named one at a time, because the question is never "is this a file?"
+ # but "should a model be handed this one?"
+ it 'does not offer a customer their own subject access export' do
+ expect(Spree.agent_attachments.find('data_requests')).to be_nil
+ end
+
+ it 'does not offer the product a customer paid for' do
+ expect(Spree.agent_attachments.find('digital_assets')).to be_nil
+ end
+
+ it 'offers the paperwork a merchant would otherwise open by hand' do
+ expect(Spree.agent_attachments.map(&:resource)).to include('orders', 'shipping_labels')
+ end
+ end
+end
diff --git a/spree/mcp/lib/spree/mcp/attachments.rb b/spree/mcp/lib/spree/mcp/attachments.rb
new file mode 100644
index 0000000000..1d2e80dbb3
--- /dev/null
+++ b/spree/mcp/lib/spree/mcp/attachments.rb
@@ -0,0 +1,126 @@
+module Spree
+ module Mcp
+ # The files attached to records, offered as MCP resources.
+ #
+ # A buyer's purchase order, a shipping label, an uploaded import — the
+ # paperwork a merchant would otherwise have to open themselves and
+ # describe. Handed over as bytes rather than extracted text: the model
+ # reading it already understands PDFs and images, so converting first
+ # would lose the layout a document carries its meaning in.
+ #
+ # Which files exist here is {Spree.agent_attachments}' decision, and what
+ # a caller may read is their record's own permission.
+ module Attachments
+ URI_SCHEME = 'spree+file'.freeze
+
+ # Base64 adds a third again on the wire, and the body is read into
+ # memory to send it. Beyond this a file is named and sized but not
+ # inlined — the merchant opens it in the dashboard instead.
+ MAX_INLINE_BYTES = 4_000_000
+
+ # Per resource, newest first. A store accumulates these indefinitely and
+ # every descriptor is sent on each listing.
+ LISTING_LIMIT = 25
+
+ class << self
+ # @param context [Spree::AgentTools::Context]
+ # @return [Array<Hash>] MCP resource descriptors
+ def list(context)
+ Spree.agent_attachments.flat_map do |entry|
+ records_for(entry, context).filter_map do |record|
+ file = entry.attached(record)
+ descriptor(entry, record, file) if file
+ end
+ end
+ end
+
+ # @param context [Spree::AgentTools::Context]
+ # @param uri [String]
+ # @return [Array<Hash>, nil] contents, or nil when there is no such
+ # file this caller may read
+ def read(context, uri)
+ entry, record = resolve(context, uri)
+ return if record.nil?
+
+ file = entry.attached(record)
+ return if file.nil?
+
+ blob = file.blob
+ return [too_large(uri, blob)] if blob.byte_size > MAX_INLINE_BYTES
+
+ [{
+ uri: uri,
+ mimeType: blob.content_type.presence || 'application/octet-stream',
+ blob: Base64.strict_encode64(file.download)
+ }]
+ end
+
+ private
+
+ def records_for(entry, context)
+ entry.scope_for(context).limit(LISTING_LIMIT)
+ rescue StandardError
+ []
+ end
+
+ # `spree+file://orders/or_123` — the resource names which map entry
+ # answers, so two resources carrying a file of the same name never
+ # collide.
+ def resolve(context, uri)
+ resource, id = uri.to_s.delete_prefix("#{URI_SCHEME}://").split('/', 2)
+ entry = Spree.agent_attachments.find(resource)
+ return [nil, nil] if entry.nil? || id.blank?
+ return [nil, nil] unless entry.readable_by?(context)
+
+ # Found through the resource's own scope, so a record in another
+ # store is indistinguishable from one that does not exist.
+ [entry, entry.resource_entry.scope_for(context).find_by_prefix_id(id)]
+ rescue StandardError
+ [nil, nil]
+ end
+
+ def descriptor(entry, record, file)
+ blob = file.blob
+
+ {
+ uri: "#{URI_SCHEME}://#{entry.resource}/#{record.prefixed_id}",
+ name: blob.filename.to_s,
+ title: title_for(entry, record, blob),
+ description: "Attached #{blob.created_at.to_date.to_fs(:long)}",
+ mimeType: blob.content_type.presence || 'application/octet-stream',
+ size: blob.byte_size
+ }
+ end
+
+ # "Purchase order for R1001", or just "Media file" where the record
+ # has no name of its own beyond the file's — repeating the filename
+ # in the title tells the model nothing twice.
+ def title_for(entry, record, blob)
+ owner = label_for(record)
+ return entry.label if owner.blank? || owner == blob.filename.to_s
+
+ "#{entry.label} for #{owner}"
+ end
+
+ # What a merchant calls the record this file hangs off.
+ def label_for(record)
+ %i[number name].each do |method|
+ value = record.public_send(method) if record.respond_to?(method)
+ return value.to_s if value.present?
+ end
+
+ nil
+ end
+
+ def too_large(uri, blob)
+ {
+ uri: uri,
+ mimeType: 'text/plain',
+ text: "This file is #{ActiveSupport::NumberHelper.number_to_human_size(blob.byte_size)}, " \
+ 'too large to read here. Open it from the dashboard instead.'
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/mcp/lib/spree/mcp/server.rb b/spree/mcp/lib/spree/mcp/server.rb
index 6f23484bd0..48a3a932e4 100644
--- a/spree/mcp/lib/spree/mcp/server.rb
+++ b/spree/mcp/lib/spree/mcp/server.rb
@@ -30,9 +30,12 @@ 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 finished export is also an MCP resource. After create_export, read
- its contents from resources rather than reporting a download path —
- the path is for the merchant, the resource is for you.
+ 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
+ resource is for you. So are the documents attached to records — a
+ buyer's purchase order, a shipping label — which come back as the
+ file itself for you to read.
TEXT
class << self
@@ -48,13 +51,14 @@ module Spree
server_context: { store_id: context.store.id }
)
- register_exports(server, context)
+ register_resources(server, context)
server
end
- # Finished exports, as resources the client may fetch.
+ # The files a client may fetch: finished exports, and the documents
+ # attached to records — a buyer's purchase order, a shipping label.
#
- # A tool result has to fit the model's context; an export does not, so
+ # A tool result has to fit the model's context; a file does not, so
# `create_export` hands back an id rather than a file. Resources are
# the protocol's answer: the client sees what exists and fetches a
# body only when it decides to.
@@ -63,13 +67,19 @@ module Spree
# the store and on what this grant may read — both known only per
# request. The closure carries the caller, so a resource one
# credential can see is never offered to another.
- def register_exports(server, context)
- server.resources_list_handler { Exports.list(context) }
+ #
+ # The protocol allows one handler of each kind, so the sources are
+ # composed here: each owns which of its records the caller may see,
+ # and each answers only for its own URI scheme.
+ SOURCES = [Exports, Attachments].freeze
+
+ def register_resources(server, context)
+ server.resources_list_handler { SOURCES.flat_map { |source| source.list(context) } }
server.resources_read_handler do |params|
uri = params[:uri] || params['uri']
- contents = Exports.read(context, uri)
- # An export another store owns, or one this grant may not read, is
+ contents = SOURCES.lazy.filter_map { |source| source.read(context, uri) }.first
+ # A file another store owns, or one this grant may not read, is
# indistinguishable from one that does not exist — the same answer
# the tools give, so a probe learns nothing either way.
raise ::MCP::Server::ResourceNotFoundError.new(uri, params) if contents.nil?
diff --git a/spree/mcp/lib/spree_mcp.rb b/spree/mcp/lib/spree_mcp.rb
index 6818a27394..375a23c0b4 100644
--- a/spree/mcp/lib/spree_mcp.rb
+++ b/spree/mcp/lib/spree_mcp.rb
@@ -3,6 +3,7 @@ require 'spree_api'
require 'mcp'
require 'spree/mcp/exports'
+require 'spree/mcp/attachments'
require 'spree/mcp/tool_adapter'
require 'spree/mcp/server'
require 'spree/mcp/engine'
diff --git a/spree/mcp/spec/lib/spree/mcp/attachments_spec.rb b/spree/mcp/spec/lib/spree/mcp/attachments_spec.rb
new file mode 100644
index 0000000000..6df3bfb0c4
--- /dev/null
+++ b/spree/mcp/spec/lib/spree/mcp/attachments_spec.rb
@@ -0,0 +1,124 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Mcp::Attachments do
+ let(:store) { @default_store }
+ let(:user) { create(:admin_user) }
+
+ def context_for(scopes)
+ Spree::AgentTools::Context.new(store: store, user: user, granted_scopes: scopes)
+ end
+
+ def order_with_po(store: @default_store, po_number: 'PO-4471')
+ create(:order, store: store).tap do |order|
+ order.po_number = po_number
+ order.po_document.attach(io: StringIO.new("%PDF-1.4\ntrailer<<>>\n%%EOF\n"),
+ filename: 'buyer-po.pdf', content_type: 'application/pdf')
+ order.save(validate: false)
+ end
+ end
+
+ describe 'what the registry decides' do
+ # The point of the registry: one registration serves any resource, and a
+ # file nobody registered is not reachable however it is addressed.
+ it 'offers a registered attachment' do
+ order = order_with_po
+
+ resource = described_class.list(context_for(['read_orders'])).first
+
+ expect(resource[:uri]).to eq("spree+file://orders/#{order.prefixed_id}")
+ expect(resource[:name]).to eq('buyer-po.pdf')
+ expect(resource[:title]).to eq("Purchase order for #{order.number}")
+ expect(resource[:mimeType]).to eq('application/pdf')
+ end
+
+ # A subject access export is one customer's entire personal data, and a
+ # digital asset is the product someone paid for. Neither is registered,
+ # and naming one directly must not reach it.
+ it 'cannot reach an attachment nobody registered' do
+ expect(Spree.agent_attachments.find('data_requests')).to be_nil
+ expect(Spree.agent_attachments.find('digital_assets')).to be_nil
+
+ contents = described_class.read(context_for(['read_all']), 'spree+file://data_requests/dr_whatever')
+
+ expect(contents).to be_nil
+ end
+
+ it 'leaves out a record carrying no file' do
+ order_with_po
+ create(:order, store: store)
+
+ expect(described_class.list(context_for(['read_orders'])).size).to eq(1)
+ end
+ end
+
+ # The registry says which files exist; the resource map says who may read
+ # them. Keeping the two apart is what stops a file becoming a way around a
+ # permission the merchant withheld.
+ describe 'the permission a file rides' do
+ it 'is the one its own resource declares' do
+ entry = Spree.agent_attachments.find('orders')
+
+ expect(entry.resource_entry.permission).to eq('read_orders')
+ expect(entry.readable_by?(context_for(['read_orders']))).to be(true)
+ expect(entry.readable_by?(context_for(['read_products']))).to be(false)
+ end
+ end
+
+ describe 'what a grant may see' do
+ before { order_with_po }
+
+ # Each file rides its own record's permission, so one grant never opens
+ # another resource's paperwork.
+ it 'offers nothing for a resource the grant cannot read' do
+ expect(described_class.list(context_for(['read_products']))).to be_empty
+ end
+
+ it 'refuses to read one the grant cannot reach' do
+ order = Spree::Order.last
+
+ expect(described_class.read(context_for(['read_products']), "spree+file://orders/#{order.prefixed_id}")).to be_nil
+ end
+ end
+
+ describe 'reading one' do
+ let!(:order) { order_with_po }
+ let(:uri) { "spree+file://orders/#{order.prefixed_id}" }
+
+ # Handed over as bytes rather than extracted text: the model already
+ # understands PDFs and images, and converting first would lose the layout
+ # a document carries its meaning in.
+ it 'returns the file itself, base64 encoded' do
+ content = described_class.read(context_for(['read_orders']), uri).first
+
+ expect(content[:mimeType]).to eq('application/pdf')
+ expect(Base64.strict_decode64(content[:blob])).to start_with('%PDF')
+ end
+
+ # Another store's file is indistinguishable from one that does not exist,
+ # so a probe learns nothing either way.
+ it 'cannot reach a file belonging to another store' do
+ theirs = order_with_po(store: create(:store, code: "other-#{SecureRandom.hex(4)}"), po_number: 'PO-THEIRS')
+
+ expect(described_class.read(context_for(['read_orders']), "spree+file://orders/#{theirs.prefixed_id}")).to be_nil
+ end
+
+ it 'answers nothing for a uri naming no record' do
+ expect(described_class.read(context_for(['read_orders']), 'spree+file://orders/or_nonsense')).to be_nil
+ end
+
+ it 'answers nothing for a malformed uri' do
+ expect(described_class.read(context_for(['read_orders']), 'spree+file://orders')).to be_nil
+ end
+
+ # Base64 adds a third again on the wire and the body is read into memory
+ # to send it, so a large file is named and sized rather than inlined.
+ it 'declines to inline a file beyond the cap' do
+ stub_const("#{described_class}::MAX_INLINE_BYTES", 8)
+
+ content = described_class.read(context_for(['read_orders']), uri).first
+
+ expect(content[:blob]).to be_nil
+ expect(content[:text]).to include('too large')
+ end
+ end
+end