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 finished exports as MCP resources

Damian Legawiecc7163a06b436
diff --git a/spree/mcp/lib/spree/mcp/exports.rb b/spree/mcp/lib/spree/mcp/exports.rb
new file mode 100644
index 0000000000..3c065ad1b0
--- /dev/null
+++ b/spree/mcp/lib/spree/mcp/exports.rb
@@ -0,0 +1,98 @@
+module Spree
+ module Mcp
+ # Finished exports, offered as MCP resources.
+ #
+ # A tool result has to fit the model's context; an export does not. A
+ # catalog of ten thousand products is megabytes of CSV, which is why
+ # `create_export` hands back an id rather than a file. Resources are the
+ # protocol's answer to that: the client sees what exists, and fetches a
+ # body only when it decides to.
+ #
+ # Reading one costs the same permission as reading the records it holds —
+ # a customers export needs what a customer needs — so the file cannot
+ # become a way around a scope the merchant withheld.
+ module Exports
+ URI_SCHEME = 'spree+export'.freeze
+
+ # Beyond this the body is not something a model can usefully read, and
+ # returning it would push out the conversation that asked for it. The
+ # client is told the size, so it can offer the download instead.
+ MAX_INLINE_BYTES = 1_000_000
+
+ class << self
+ # @param context [Spree::AgentTools::Context]
+ # @return [Array<Hash>] MCP resource descriptors
+ def list(context)
+ readable(context).map { |export| descriptor(export) }
+ end
+
+ # @param context [Spree::AgentTools::Context]
+ # @param uri [String]
+ # @return [Array<Hash>, nil] contents, or nil when there is no such
+ # export this caller may read
+ def read(context, uri)
+ export = find(context, uri)
+ return if export.nil?
+
+ blob = export.attachment.blob
+ return [too_large(uri, blob)] if blob.byte_size > MAX_INLINE_BYTES
+
+ [{ uri: uri, mimeType: 'text/csv', text: export.attachment.download }]
+ end
+
+ private
+
+ # Finished exports of this store that the caller's grant covers.
+ #
+ # `done?` rather than every export: an unfinished one has no file, and
+ # naming it would have the model fetch something that cannot be read.
+ def readable(context)
+ context.store.exports.
+ select { |export| export.done? && permitted?(context, export) }.
+ sort_by(&:created_at).reverse
+ end
+
+ def find(context, uri)
+ id = uri.to_s.delete_prefix("#{URI_SCHEME}://")
+ export = context.store.exports.find_by_prefix_id(id)
+ return unless export&.done? && permitted?(context, export)
+
+ export
+ rescue StandardError
+ nil
+ end
+
+ # The scope the exported records themselves need. An export whose type
+ # declares none is readable only by a credential holding everything,
+ # which is how the Admin API treats an unmapped type.
+ def permitted?(context, export)
+ scope = export.class.try(:required_scope)
+ return context.holds?('read_all') if scope.blank?
+
+ context.holds?("read_#{scope}")
+ end
+
+ def descriptor(export)
+ {
+ uri: "#{URI_SCHEME}://#{export.prefixed_id}",
+ name: export.attachment.blob.filename.to_s,
+ title: "#{export.class.name.demodulize.underscore.humanize} export",
+ description: "Generated #{export.created_at.to_date.to_fs(:long)}",
+ mimeType: 'text/csv',
+ size: export.attachment.blob.byte_size
+ }
+ end
+
+ def too_large(uri, blob)
+ {
+ uri: uri,
+ mimeType: 'text/plain',
+ text: "This export is #{ActiveSupport::NumberHelper.number_to_human_size(blob.byte_size)}, " \
+ 'too large to read here. Download it from the dashboard, or narrow the export with ' \
+ 'filters and create a smaller one.'
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/mcp/lib/spree/mcp/server.rb b/spree/mcp/lib/spree/mcp/server.rb
index ff82620adf..84d655cd56 100644
--- a/spree/mcp/lib/spree/mcp/server.rb
+++ b/spree/mcp/lib/spree/mcp/server.rb
@@ -31,7 +31,7 @@ module Spree
# @param context [Spree::AgentTools::Context] who is asking, and where
# @return [MCP::Server]
def for(context)
- ::MCP::Server.new(
+ server = ::MCP::Server.new(
name: 'spree-admin',
title: "#{context.store.name} (Spree admin)",
version: Spree.version,
@@ -39,6 +39,35 @@ module Spree
tools: tools_for(context),
server_context: { store_id: context.store.id }
)
+
+ register_exports(server, context)
+ server
+ end
+
+ # Finished exports, as resources the client may fetch.
+ #
+ # A tool result has to fit the model's context; an export 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.
+ #
+ # Handlers rather than a fixed list, because what exists depends on
+ # 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) }
+
+ 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
+ # 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?
+
+ contents
+ end
end
# The tools this caller may use, as MCP definitions.
diff --git a/spree/mcp/lib/spree_mcp.rb b/spree/mcp/lib/spree_mcp.rb
index c12388d8b6..6818a27394 100644
--- a/spree/mcp/lib/spree_mcp.rb
+++ b/spree/mcp/lib/spree_mcp.rb
@@ -2,6 +2,7 @@ require 'spree_core'
require 'spree_api'
require 'mcp'
+require 'spree/mcp/exports'
require 'spree/mcp/tool_adapter'
require 'spree/mcp/server'
require 'spree/mcp/engine'
diff --git a/spree/mcp/spec/lib/spree/mcp/exports_spec.rb b/spree/mcp/spec/lib/spree/mcp/exports_spec.rb
new file mode 100644
index 0000000000..1c0bd2aa03
--- /dev/null
+++ b/spree/mcp/spec/lib/spree/mcp/exports_spec.rb
@@ -0,0 +1,74 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Mcp::Exports 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 finished_export(klass, store: @default_store)
+ klass.create!(store: store, user: user, format: 'csv').tap do |export|
+ export.attachment.attach(io: StringIO.new("id,name\n1,Thing\n"),
+ filename: 'export.csv', content_type: 'text/csv')
+ end
+ end
+
+ # Reading an export costs what reading the records costs. Otherwise a file
+ # becomes the way around a scope the merchant deliberately withheld.
+ describe 'what a grant may see' do
+ before do
+ finished_export(Spree::Exports::Products)
+ finished_export(Spree::Exports::Orders)
+ end
+
+ it 'offers only the exports the grant covers' do
+ titles = described_class.list(context_for(['read_orders'])).map { |r| r[:title] }
+
+ expect(titles).to all(include('Orders'))
+ expect(titles.join).not_to include('Products')
+ end
+
+ it 'refuses to read one the grant does not cover' do
+ products = Spree::Exports::Products.last
+
+ expect(described_class.read(context_for(['read_orders']),
+ "spree+export://#{products.prefixed_id}")).to be_nil
+ end
+ end
+
+ describe 'another store' do
+ let(:other_store) { create(:store, code: "other-#{SecureRandom.hex(4)}") }
+
+ it 'cannot see or read this store\'s exports' do
+ export = finished_export(Spree::Exports::Products)
+ elsewhere = Spree::AgentTools::Context.new(store: other_store, user: user,
+ granted_scopes: ['read_all'])
+
+ expect(described_class.list(elsewhere)).to be_empty
+ expect(described_class.read(elsewhere, "spree+export://#{export.prefixed_id}")).to be_nil
+ end
+ end
+
+ # An unfinished export has no file, and naming it would send the model after
+ # something it cannot read.
+ it 'leaves out an export that has not finished' do
+ Spree::Exports::Products.create!(store: store, user: user, format: 'csv')
+
+ expect(described_class.list(context_for(['read_all']))).to be_empty
+ end
+
+ # Past a point the body is not something a model can usefully read, and
+ # returning it would push out the conversation that asked for it.
+ it 'describes a file too large to return instead of returning it' do
+ export = finished_export(Spree::Exports::Products)
+ allow(export.attachment.blob).to receive(:byte_size).and_return(described_class::MAX_INLINE_BYTES + 1)
+ allow_any_instance_of(Spree::Exports::Products).to receive(:attachment).and_return(export.attachment)
+
+ contents = described_class.read(context_for(['read_all']), "spree+export://#{export.prefixed_id}")
+
+ expect(contents.first[:mimeType]).to eq('text/plain')
+ expect(contents.first[:text]).to include('too large')
+ end
+end