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.

Add the spree_mcp gem serving the agent tools over MCP

Damian Legawiec477ba05011d5
diff --git a/scripts/test/rspec b/scripts/test/rspec
index 90bced7982..ab77b98304 100755
--- a/scripts/test/rspec
+++ b/scripts/test/rspec
@@ -6,7 +6,7 @@
# scripts/test/rspec api spec/controllers/spree/api/v3/admin/orders_controller_spec.rb:12
# # targeted: background priority, no queue
#
-# Engines: core, api, emails, dashboard, opentelemetry, easypost, meilisearch, stripe.
+# Engines: core, api, emails, dashboard, mcp, opentelemetry, easypost, meilisearch, stripe.
# Everything after the engine is passed to rspec; with nothing after it the whole
# suite runs through parallel_rspec.
#
diff --git a/spree/mcp/Gemfile b/spree/mcp/Gemfile
new file mode 100644
index 0000000000..bcb6bab621
--- /dev/null
+++ b/spree/mcp/Gemfile
@@ -0,0 +1,5 @@
+eval_gemfile('../common_spree_dependencies.rb')
+
+gem 'spree', path: '../'
+
+gemspec
diff --git a/spree/mcp/LICENSE b/spree/mcp/LICENSE
new file mode 100644
index 0000000000..b64b902aef
--- /dev/null
+++ b/spree/mcp/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026-present, Vendo Sp. z o.o., Vendo Connect Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/spree/mcp/Rakefile b/spree/mcp/Rakefile
new file mode 100644
index 0000000000..79efae6cb0
--- /dev/null
+++ b/spree/mcp/Rakefile
@@ -0,0 +1,15 @@
+require 'rubygems'
+require 'rake'
+require 'rake/testtask'
+require 'rspec/core/rake_task'
+require 'spree/testing_support/common_rake'
+
+RSpec::Core::RakeTask.new
+
+task default: :spec
+
+desc "Generates a dummy app for testing"
+task :test_app do
+ ENV['LIB_NAME'] = 'spree_mcp'
+ Rake::Task['common:test_app'].invoke
+end
diff --git a/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb
new file mode 100644
index 0000000000..15b8e4d642
--- /dev/null
+++ b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb
@@ -0,0 +1,91 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # The MCP endpoint: `POST /api/v3/admin/mcp`.
+ #
+ # An ordinary admin API controller rather than the gem's Rack
+ # transport, which takes one pre-built server for every request and so
+ # cannot carry a per-request principal. Here the key authenticates
+ # through the concern every other admin endpoint uses, selects the
+ # store the same way, and gets a server built for it alone.
+ #
+ # Stateless: one JSON-RPC message per request, one JSON response, no
+ # session and no server-to-client stream, so any Puma worker answers
+ # any request.
+ #
+ # See docs/plans/6.0-mcp-server.md.
+ class McpController < Spree::Api::V3::Admin::BaseController
+ # The scope gate is per tool, not per request: a call carries the
+ # tool it wants inside the JSON-RPC body, and every tool already
+ # declares the permission it needs. Checking one scope for the whole
+ # endpoint would mean either refusing a key that may legitimately
+ # read, or waving through a write the key cannot make.
+ skip_scope_check!
+
+ # Prepended so it answers before the inherited authentication does.
+ # The generic "Authentication required" is useless to an agent: this
+ # text is what both the model and the person actually read when a
+ # client is misconfigured, so it has to say which header to set and
+ # where a key comes from.
+ #
+ # It also makes this a machine-only surface. A JWT belongs to a
+ # signed-in admin, and a browser session is not what should drive an
+ # agent — the dashboard assistant is that path, over the same
+ # registry.
+ prepend_before_action :require_secret_key!
+
+ def create
+ render json: server.handle_json(request.body.read), content_type: 'application/json'
+ end
+
+ protected
+
+ # The key in either of the two forms clients offer. Several MCP
+ # clients have a bearer-token field and no way to set a custom
+ # header, so a secret key is accepted there too. The `sk_` prefix
+ # keeps it unambiguous against the JWTs the Admin API also accepts
+ # in `Authorization`, and a JWT presented here resolves to no key
+ # and is refused below.
+ def extract_api_key
+ super.presence || bearer_secret_key
+ end
+
+ private
+
+ def bearer_secret_key
+ token = request.headers['Authorization'].to_s[/\ABearer\s+(.+)\z/i, 1]
+
+ token if token.to_s.start_with?(Spree::ApiKey::PREFIXES['secret'])
+ end
+
+ def server
+ Spree::Mcp::Server.for(agent_context)
+ end
+
+ def agent_context
+ Spree::AgentTools::Context.new(store: current_store, api_key: current_api_key)
+ end
+
+ # The error text is what both the model and the person read, so it
+ # says which header to set and where the key comes from rather than
+ # only that something was missing.
+ def require_secret_key!
+ return if secret_api_key.present?
+
+ render json: {
+ jsonrpc: '2.0',
+ id: nil,
+ error: {
+ code: -32_001,
+ message: 'A Spree secret API key is required. Send it as `X-Spree-API-Key: sk_…` ' \
+ 'or `Authorization: Bearer sk_…`. Mint one in the dashboard under ' \
+ 'Settings → API keys, granting only the scopes this agent needs.'
+ }
+ }, status: :unauthorized
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/mcp/config/routes.rb b/spree/mcp/config/routes.rb
new file mode 100644
index 0000000000..31f79c84bd
--- /dev/null
+++ b/spree/mcp/config/routes.rb
@@ -0,0 +1,12 @@
+Spree::Core::Engine.add_routes do
+ namespace :api, defaults: { format: 'json' } do
+ namespace :v3 do
+ namespace :admin do
+ # One JSON-RPC message per request. Drawn inside the admin namespace so
+ # the endpoint inherits the Admin API's authentication, rate limiting
+ # and security headers rather than reimplementing them.
+ post 'mcp', to: 'mcp#create'
+ end
+ end
+ end
+end
diff --git a/spree/mcp/lib/spree/mcp/engine.rb b/spree/mcp/lib/spree/mcp/engine.rb
new file mode 100644
index 0000000000..574ddf3ba2
--- /dev/null
+++ b/spree/mcp/lib/spree/mcp/engine.rb
@@ -0,0 +1,16 @@
+module Spree
+ module Mcp
+ class Engine < ::Rails::Engine
+ isolate_namespace Spree
+ engine_name 'spree_mcp'
+ end
+ end
+end
+
+# The endpoint is drawn into the Admin API's own namespace rather than mounted
+# separately, so it inherits that namespace's host constraints, rate limiting
+# and security headers. Required here rather than left to Rails' engine route
+# loading: `Spree::Core::Engine.add_routes` has to have collected the block
+# before core draws its routes, which happens while core's own routes file
+# loads.
+require_relative '../../../config/routes'
diff --git a/spree/mcp/lib/spree/mcp/server.rb b/spree/mcp/lib/spree/mcp/server.rb
new file mode 100644
index 0000000000..ff82620adf
--- /dev/null
+++ b/spree/mcp/lib/spree/mcp/server.rb
@@ -0,0 +1,59 @@
+module Spree
+ module Mcp
+ # Builds an `MCP::Server` for one caller.
+ #
+ # Per request, not per process. A server carries the tools its caller may
+ # use and nothing else — a key minted to read orders is never told a
+ # refund tool exists — so the tool list cannot be shared between
+ # principals, and the gem's own Rack transport (one server for every
+ # request) is not what mounts this. An ordinary admin API controller does,
+ # and hands the JSON-RPC message to {MCP::Server#handle_json}.
+ module Server
+ # What the model is told about using this server at discovery, so it
+ # reaches for the discovery tools before guessing at names and filters.
+ INSTRUCTIONS = <<~TEXT.freeze
+ This server manages one Spree store's back office.
+
+ Start with describe_resource to learn which resources exist and which
+ fields each can be filtered and sorted by, then search_resources to find
+ records and get_resource to read one in full. For numbers — revenue,
+ orders, units — use describe_reporting and then query_report rather than
+ counting records yourself.
+
+ Writes are named after what they do: a tool per operation, each running
+ the same workflow the dashboard runs, so validations and notifications
+ behave identically. Record arguments are prefixed ids as they appear in
+ search results. You are only offered the tools this credential permits,
+ so a tool you cannot see is one this store has not granted.
+ TEXT
+
+ class << self
+ # @param context [Spree::AgentTools::Context] who is asking, and where
+ # @return [MCP::Server]
+ def for(context)
+ ::MCP::Server.new(
+ name: 'spree-admin',
+ title: "#{context.store.name} (Spree admin)",
+ version: Spree.version,
+ instructions: INSTRUCTIONS,
+ tools: tools_for(context),
+ server_context: { store_id: context.store.id }
+ )
+ end
+
+ # The tools this caller may use, as MCP definitions.
+ #
+ # Filtering happens here rather than at call time, so a tool the
+ # credential cannot use is never named to the model — and a call to
+ # something it was not offered is "unknown tool", not "forbidden",
+ # which says less about what else exists.
+ #
+ # @param context [Spree::AgentTools::Context]
+ # @return [Array<Class<MCP::Tool>>]
+ def tools_for(context)
+ Spree.agent_tools.available_for(context).map { |tool| ToolAdapter.build(tool) }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/mcp/lib/spree/mcp/tool_adapter.rb b/spree/mcp/lib/spree/mcp/tool_adapter.rb
new file mode 100644
index 0000000000..d3406a928b
--- /dev/null
+++ b/spree/mcp/lib/spree/mcp/tool_adapter.rb
@@ -0,0 +1,106 @@
+module Spree
+ module Mcp
+ # Turns a {Spree::AgentTool} into an `MCP::Tool` the protocol can offer.
+ #
+ # The whole adapter: a name, a description, the tool's parameter schema as
+ # JSON Schema, and a handler that runs the tool and shapes what comes back.
+ # Nothing about a tool is written twice — a tool registered by an extension
+ # is offered over MCP with no MCP code anywhere near it.
+ module ToolAdapter
+ class << self
+ # @param tool [Spree::AgentTool] instantiated for the caller's context
+ # @return [Class<MCP::Tool>]
+ def build(tool)
+ # The block is instance_exec'd on the generated tool class, so it
+ # cannot call back into this module by name — `adapter` closes over
+ # it instead.
+ adapter = self
+
+ ::MCP::Tool.define(
+ name: tool.tool_name,
+ description: tool.description,
+ input_schema: input_schema(tool),
+ annotations: annotations(tool)
+ ) { |**arguments| adapter.respond(tool, arguments) }
+ end
+
+ # The tool's declared params as JSON Schema.
+ #
+ # @param tool [Spree::AgentTool]
+ # @return [Hash]
+ def input_schema(tool)
+ properties = tool.params.to_h do |name, options|
+ property = { type: json_type(options[:type]) }
+ property[:description] = options[:description] if options[:description].present?
+ property[:items] = { type: 'object' } if property[:type] == 'array'
+
+ [name.to_s, property]
+ end
+
+ {
+ type: 'object',
+ properties: properties,
+ required: tool.params.select { |_name, options| options[:required] }.keys.map(&:to_s)
+ }
+ end
+
+ # Clients that gate confirmation on annotations rather than on a
+ # server's word need both hints set explicitly: the gem defaults
+ # `destructiveHint` to true, so a read tool that says nothing would be
+ # confirmed like a deletion.
+ #
+ # @return [Hash]
+ def annotations(tool)
+ { read_only_hint: !tool.mutating?, destructive_hint: tool.mutating?, idempotent_hint: !tool.mutating? }
+ end
+
+ # A tool answers with a plain hash. A hash carrying `:error` is the
+ # tool refusing — the model should read it and correct itself, so it
+ # comes back as a tool error rather than a protocol error, which the
+ # model never sees.
+ #
+ # Public because the definition block calls it through a closure.
+ #
+ # @param tool [Spree::AgentTool]
+ # @param arguments [Hash]
+ # @return [MCP::Tool::Response]
+ def respond(tool, arguments)
+ result = tool.call(**arguments.symbolize_keys.except(:server_context))
+
+ if result.is_a?(Hash) && result[:error].present?
+ ::MCP::Tool::Response.new([{ type: 'text', text: result[:error].to_s }], error: true)
+ else
+ ::MCP::Tool::Response.new([{ type: 'text', text: text_for(result) }], structured_content: result)
+ end
+ rescue ArgumentError => e
+ # A missing or unknown keyword means the model filled the schema in
+ # wrongly; naming the parameter lets it retry correctly.
+ ::MCP::Tool::Response.new([{ type: 'text', text: e.message }], error: true)
+ end
+
+ private
+
+ # A tool declares Ruby-ish types; JSON Schema wants its own names, and
+ # anything unrecognised is a string, which every client can render.
+ def json_type(type)
+ case type&.to_sym
+ when :boolean then 'boolean'
+ when :integer then 'integer'
+ when :number, :float, :decimal then 'number'
+ when :object, :hash then 'object'
+ when :array then 'array'
+ else 'string'
+ end
+ end
+
+ # A line the client can show beside its confirmation prompt, and the
+ # model can read without parsing the structured payload.
+ def text_for(result)
+ return result.to_s unless result.is_a?(Hash)
+
+ result[:summary].presence || JSON.generate(result)
+ end
+ end
+ end
+ end
+end
diff --git a/spree/mcp/lib/spree_mcp.rb b/spree/mcp/lib/spree_mcp.rb
new file mode 100644
index 0000000000..c12388d8b6
--- /dev/null
+++ b/spree/mcp/lib/spree_mcp.rb
@@ -0,0 +1,20 @@
+require 'spree_core'
+require 'spree_api'
+require 'mcp'
+
+require 'spree/mcp/tool_adapter'
+require 'spree/mcp/server'
+require 'spree/mcp/engine'
+
+module Spree
+ # A Model Context Protocol server for the Spree back office.
+ #
+ # A thin protocol adapter over {Spree.agent_tools}: the tools, their schemas
+ # and the permissions gating them all live in `spree_core`, so this gem adds
+ # a transport and nothing else. Optional — an installation that does not
+ # want an MCP endpoint simply does not load it.
+ #
+ # See docs/plans/6.0-mcp-server.md.
+ module Mcp
+ end
+end
diff --git a/spree/mcp/spec/lib/spree/mcp/server_spec.rb b/spree/mcp/spec/lib/spree/mcp/server_spec.rb
new file mode 100644
index 0000000000..1967cc226d
--- /dev/null
+++ b/spree/mcp/spec/lib/spree/mcp/server_spec.rb
@@ -0,0 +1,166 @@
+require 'spec_helper'
+
+# The protocol layer, exercised the way a client exercises it: by handing the
+# server a JSON-RPC string and reading what comes back. No LLM anywhere — an
+# MCP client is a JSON-RPC sender, so the whole surface is testable with
+# factories and strings.
+RSpec.describe Spree::Mcp::Server do
+ let(:store) { @default_store }
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: scopes) }
+ let(:scopes) { ['read_all'] }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+ let(:server) { described_class.for(context) }
+
+ def call(method, **params)
+ message = { jsonrpc: '2.0', id: 1, method: method }
+ message[:params] = params if params.any?
+
+ JSON.parse(server.handle_json(message.to_json))
+ end
+
+ describe 'initialize' do
+ it 'answers with the store name and usage instructions' do
+ result = call('initialize', protocolVersion: '2026-07-28', capabilities: {},
+ clientInfo: { name: 'rspec', version: '1' })['result']
+
+ expect(result.dig('serverInfo', 'name')).to eq('spree-admin')
+ expect(result['instructions']).to include('describe_resource')
+ end
+ end
+
+ describe 'tools/list' do
+ let(:tools) { call('tools/list').dig('result', 'tools') }
+ let(:names) { tools.map { |tool| tool['name'] } }
+
+ context 'with a read-only key' do
+ let(:scopes) { ['read_all'] }
+
+ it 'offers the read tools' do
+ expect(names).to include('search_resources', 'get_resource', 'describe_resource')
+ end
+
+ it 'offers no tool that changes store data' do
+ expect(names).not_to include('create_resource', 'update_resource', 'delete_resource')
+ end
+
+ it 'does not name a workflow tool the key could not run' do
+ expect(names).not_to include('orders_cancel', 'products_update')
+ end
+
+ it 'marks a search read-only, so a client need not prompt for it' do
+ search = tools.find { |tool| tool['name'] == 'search_resources' }
+
+ expect(search.dig('annotations', 'readOnlyHint')).to be(true)
+ expect(search.dig('annotations', 'destructiveHint')).to be(false)
+ end
+
+ # An export changes nothing, but it produces a file of store data and
+ # mails a link to it — that leaves the building, so it is annotated for
+ # confirmation even though the key only reads.
+ it 'still marks an export for confirmation' do
+ export = tools.find { |tool| tool['name'] == 'create_export' }
+
+ expect(export.dig('annotations', 'destructiveHint')).to be(true)
+ end
+ end
+
+ context 'with a key scoped to one resource' do
+ let(:scopes) { ['write_products'] }
+
+ it 'offers that resource\'s workflow tools' do
+ expect(names).to include('products_update', 'products_activate')
+ end
+
+ it 'offers no other resource\'s write tools' do
+ expect(names).not_to include('orders_cancel', 'sellers_approve')
+ end
+ end
+
+ context 'with a full-access key' do
+ let(:scopes) { ['write_all'] }
+
+ it 'offers the workflow tools as destructive, so clients gate them' do
+ cancel = tools.find { |tool| tool['name'] == 'orders_cancel' }
+
+ expect(cancel.dig('annotations', 'destructiveHint')).to be(true)
+ expect(cancel.dig('annotations', 'readOnlyHint')).to be(false)
+ end
+
+ it 'derives each workflow tool\'s schema from the workflow itself' do
+ cancel = tools.find { |tool| tool['name'] == 'orders_cancel' }
+ properties = cancel.dig('inputSchema', 'properties')
+
+ expect(properties).to include('order', 'refund_payments', 'note')
+ expect(cancel.dig('inputSchema', 'required')).to eq(['order'])
+ end
+
+ it 'never offers the principal or the store as a parameter' do
+ cancel = tools.find { |tool| tool['name'] == 'orders_cancel' }
+ create = tools.find { |tool| tool['name'] == 'products_create' }
+
+ expect(cancel.dig('inputSchema', 'properties')).not_to have_key('canceler')
+ expect(create.dig('inputSchema', 'properties')).not_to have_key('store')
+ end
+
+ it 'hides a deprecated parameter the allowlist excludes' do
+ cancel = tools.find { |tool| tool['name'] == 'orders_cancel' }
+
+ expect(cancel.dig('inputSchema', 'properties')).not_to have_key('restock_items')
+ end
+
+ it 'gives every tool a name the protocol accepts' do
+ expect(names).to all(match(/\A[a-zA-Z0-9_-]{1,64}\z/))
+ end
+ end
+ end
+
+ describe 'tools/call' do
+ let(:scopes) { ['write_all'] }
+
+ it 'returns structured content from a read tool' do
+ create(:product, store: store, name: 'Rotary Shaver 9000')
+
+ response = call('tools/call', name: 'search_resources',
+ arguments: { 'resource' => 'products', 'filters' => { 'name_cont' => 'Rotary' } })
+
+ expect(response.dig('result', 'isError')).to be(false)
+ expect(response.dig('result', 'structuredContent', 'records').first['title']).to eq('Rotary Shaver 9000')
+ end
+
+ context 'when the caller was never offered the tool' do
+ let(:scopes) { ['read_products'] }
+
+ # A protocol-level error rather than a forbidden result: the tool was
+ # never named to this caller, so as far as this server is concerned it
+ # does not exist — which says nothing about what else the store has.
+ it 'refuses at the protocol level rather than reporting forbidden' do
+ response = call('tools/call', name: 'orders_cancel', arguments: { 'order' => 'order_abc' })
+
+ expect(response).to have_key('error')
+ expect(response['result']).to be_nil
+ expect(response.to_s.downcase).not_to include('forbidden')
+ end
+ end
+
+ it 'returns the tool\'s own refusal as a tool error the model can read' do
+ response = call('tools/call', name: 'get_resource', arguments: { 'resource' => 'products', 'id' => 'prod_missing' })
+
+ expect(response.dig('result', 'isError')).to be(true)
+ expect(response.dig('result', 'content').first['text']).to include('prod_missing')
+ end
+
+ it 'refuses an id belonging to another store' do
+ other_product = create(:product, store: create(:store, code: "other-#{SecureRandom.hex(4)}"), name: 'Not Ours')
+
+ response = call('tools/call', name: 'get_resource', arguments: { 'resource' => 'products', 'id' => other_product.prefixed_id })
+
+ expect(response.dig('result', 'isError')).to be(true)
+ end
+
+ it 'names the parameter when the arguments do not fit the schema' do
+ response = call('tools/call', name: 'get_resource', arguments: { 'resource' => 'products' })
+
+ expect(response.to_s).to include('id')
+ end
+ end
+end
diff --git a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb
new file mode 100644
index 0000000000..a640ec064c
--- /dev/null
+++ b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb
@@ -0,0 +1,154 @@
+require 'spec_helper'
+
+# The endpoint, from the header down. A request spec rather than a controller
+# spec because the unit under test is the whole request: the credential, the
+# store it selects, and a JSON-RPC body that never touches a view.
+RSpec.describe 'Admin MCP endpoint', type: :request do
+ let(:store) { @default_store }
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: scopes) }
+ let(:scopes) { ['write_all'] }
+ let(:token) { api_key.plaintext_token }
+
+ def post_rpc(method, params = nil, headers: {}, id: 1)
+ message = { jsonrpc: '2.0', id: id, method: method }
+ message[:params] = params if params
+
+ post '/api/v3/admin/mcp', params: message.to_json,
+ headers: { 'CONTENT_TYPE' => 'application/json' }.merge(headers)
+ JSON.parse(response.body)
+ end
+
+ describe 'authentication' do
+ it 'accepts the Admin API header' do
+ body = post_rpc('tools/list', headers: { 'X-Spree-API-Key' => token })
+
+ expect(response).to have_http_status(:ok)
+ expect(body['result']['tools']).to be_present
+ end
+
+ # Several MCP clients offer a bearer-token field and no custom header, so
+ # the same key is accepted there.
+ it 'accepts the key as a bearer token' do
+ body = post_rpc('tools/list', headers: { 'Authorization' => "Bearer #{token}" })
+
+ expect(response).to have_http_status(:ok)
+ expect(body['result']['tools']).to be_present
+ end
+
+ it 'refuses a request with no key, naming the header to set' do
+ body = post_rpc('tools/list')
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(body.dig('error', 'message')).to include('X-Spree-API-Key')
+ end
+
+ it 'refuses a publishable key' do
+ publishable = create(:api_key, :publishable, store: store)
+
+ post_rpc('tools/list', headers: { 'X-Spree-API-Key' => publishable.token })
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ it 'refuses a revoked key' do
+ revoked = create(:api_key, :secret, store: store)
+ plaintext = revoked.plaintext_token
+ revoked.revoke!
+
+ post_rpc('tools/list', headers: { 'X-Spree-API-Key' => plaintext })
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ # This is a machine surface: a browser session belongs to the dashboard
+ # assistant, which reads the same registry with the admin's own ability.
+ it 'refuses a JWT' do
+ post_rpc('tools/list', headers: { 'Authorization' => 'Bearer eyJhbGciOiJIUzI1NiJ9.e30.signature' })
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ describe 'tenancy' do
+ it 'serves the key\'s own store when the header agrees' do
+ body = post_rpc('tools/call',
+ { name: 'search_resources', arguments: { 'resource' => 'products' } },
+ headers: { 'X-Spree-API-Key' => token, 'X-Spree-Store-Id' => store.prefixed_id })
+
+ expect(response).to have_http_status(:ok)
+ expect(body.dig('result', 'isError')).to be(false)
+ end
+
+ # The key selects the store; a header naming a different one is refused
+ # outright rather than quietly served the key's own store.
+ it 'refuses a header naming another store' do
+ other_store = create(:store, code: "other-#{SecureRandom.hex(4)}")
+
+ post_rpc('tools/call',
+ { name: 'search_resources', arguments: { 'resource' => 'products' } },
+ headers: { 'X-Spree-API-Key' => token, 'X-Spree-Store-Id' => other_store.prefixed_id })
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it 'does not find another store\'s record' do
+ other_product = create(:product, store: create(:store, code: "other-#{SecureRandom.hex(4)}"))
+
+ body = post_rpc('tools/call',
+ { name: 'get_resource', arguments: { 'resource' => 'products', 'id' => other_product.prefixed_id } },
+ headers: { 'X-Spree-API-Key' => token })
+
+ expect(body.dig('result', 'isError')).to be(true)
+ end
+ end
+
+ describe 'running a workflow end to end' do
+ let(:order) { create(:completed_order_with_totals, store: store) }
+ let(:fulfillment) { order.shipments.first }
+
+ it 'marks a fulfillment delivered through the real workflow' do
+ fulfillment.update!(status: 'fulfilled')
+
+ body = post_rpc('tools/call',
+ { name: 'fulfillments_mark_delivered', arguments: { 'fulfillment' => fulfillment.prefixed_id } },
+ headers: { 'X-Spree-API-Key' => token })
+
+ expect(body.dig('result', 'isError')).to be(false)
+ expect(fulfillment.reload.status).to eq('delivered')
+ end
+
+ it 'records the API key as the actor when it cancels an order' do
+ reason = create(:order_cancellation_reason, store: store)
+
+ body = post_rpc('tools/call',
+ { name: 'orders_cancel',
+ arguments: { 'order' => order.prefixed_id, 'reason' => reason.prefixed_id } },
+ headers: { 'X-Spree-API-Key' => token })
+
+ expect(body.dig('result', 'isError')).to be(false)
+ expect(order.reload.status).to eq('canceled')
+ expect(order.canceler).to eq(api_key)
+ end
+
+ it 'carries the workflow\'s own refusal back as a tool error' do
+ body = post_rpc('tools/call',
+ { name: 'orders_cancel', arguments: { 'order' => 'order_nope' } },
+ headers: { 'X-Spree-API-Key' => token })
+
+ expect(body.dig('result', 'isError')).to be(true)
+ expect(body.dig('result', 'content').first['text']).to include('order')
+ end
+ end
+
+ describe 'scope filtering' do
+ let(:scopes) { ['read_orders'] }
+
+ it 'offers only what the key\'s scopes permit' do
+ body = post_rpc('tools/list', headers: { 'X-Spree-API-Key' => token })
+ names = body.dig('result', 'tools').map { |tool| tool['name'] }
+
+ expect(names).to include('search_resources')
+ expect(names).not_to include('orders_cancel')
+ end
+ end
+end
diff --git a/spree/mcp/spec/spec_helper.rb b/spree/mcp/spec/spec_helper.rb
new file mode 100644
index 0000000000..e4fb73a4ce
--- /dev/null
+++ b/spree/mcp/spec/spec_helper.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+ENV['RAILS_ENV'] ||= 'test'
+
+begin
+ require File.expand_path('../dummy/config/environment', __FILE__)
+rescue LoadError
+ puts 'Could not load dummy application. Please ensure you have run `bundle exec rake test_app`'
+end
+
+require 'rspec/rails'
+require 'database_cleaner/active_record'
+
+require 'spree/testing_support/factories'
+require 'spree/testing_support/jobs'
+require 'spree/testing_support/store'
+
+RSpec.configure do |config|
+ config.color = true
+ config.default_formatter = 'progress'
+ config.infer_spec_type_from_file_location!
+ config.mock_with :rspec
+ config.raise_errors_for_deprecations!
+ config.use_transactional_fixtures = true
+
+ config.include FactoryBot::Syntax::Methods
+
+ config.order = :random
+ Kernel.srand config.seed
+end
diff --git a/spree/mcp/spree_mcp.gemspec b/spree/mcp/spree_mcp.gemspec
new file mode 100644
index 0000000000..2e3c1c92fa
--- /dev/null
+++ b/spree/mcp/spree_mcp.gemspec
@@ -0,0 +1,32 @@
+# encoding: UTF-8
+
+require_relative '../core/lib/spree/core/version.rb'
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'spree_mcp'
+ s.version = Spree.version
+ s.authors = ['Vendo Connect Inc.', 'Vendo Sp. z o.o.']
+ s.email = '[email protected]'
+ s.summary = 'Model Context Protocol server for the Spree Admin API'
+ s.description = 'Mounts an MCP endpoint on the Spree Admin API so any MCP client can merchandise the catalog, query reports and manage store setup in plain language, under the same tenancy and permission rules as the API'
+ s.homepage = 'https://spreecommerce.org'
+ s.license = 'MIT'
+
+ s.metadata = {
+ "bug_tracker_uri" => "https://github.com/spree/spree/issues",
+ "changelog_uri" => "https://github.com/spree/spree/releases/tag/v#{s.version}",
+ "documentation_uri" => "https://docs.spreecommerce.org/",
+ "source_code_uri" => "https://github.com/spree/spree/tree/v#{s.version}",
+ }
+
+ s.required_ruby_version = '>= 3.2'
+
+ s.files = Dir["{app,config,db,lib,vendor}/**/*", "Rakefile", "LICENSE", "README.md"].reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) }
+ s.require_path = 'lib'
+
+ s.add_dependency 'spree_core', s.version
+ s.add_dependency 'spree_api', s.version
+
+ s.add_dependency 'mcp', '~> 1.5'
+end