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 dispatcher that runs a tool call through the Admin API

Damian Legawiecd6c92330e01b
diff --git a/spree/api/spec/lib/spree/agent_tools/api_dispatch_spec.rb b/spree/api/spec/lib/spree/agent_tools/api_dispatch_spec.rb
new file mode 100644
index 0000000000..3994e46fbc
--- /dev/null
+++ b/spree/api/spec/lib/spree/agent_tools/api_dispatch_spec.rb
@@ -0,0 +1,113 @@
+require 'spec_helper'
+
+# The dispatcher is the whole point of the restructure: a tool reaches data
+# through the Admin API, so a guard added there protects agents without
+# anyone copying it into the agent layer.
+RSpec.describe Spree::AgentTools::ApiDispatch do
+ let(:store) { @default_store }
+
+ def dispatcher_for(key, headers: nil)
+ context = Spree::AgentTools::Context.new(
+ store: store, api_key: key,
+ request_headers: headers || { 'HTTP_X_SPREE_API_KEY' => key.plaintext_token,
+ 'HTTP_HOST' => 'www.example.com' }
+ )
+ described_class.new(context)
+ end
+
+ let(:reader) { create(:api_key, :secret, store: store, scopes: ['read_all']) }
+
+ describe 'reaching an operation' do
+ it 'returns what the endpoint rendered' do
+ create(:product, store: store, name: 'Dispatched')
+
+ response = dispatcher_for(reader).call(method: :get, path: '/products')
+
+ expect(response).to be_success
+ expect(response.data.map { |row| row['name'] }).to include('Dispatched')
+ expect(response.meta['count']).to be_positive
+ end
+
+ # The fault this replaces: the tools called `.ransack` directly and
+ # skipped the step that decodes prefixed ids, so filtering by an id the
+ # tools themselves returned matched nothing and said so as a fact.
+ it 'filters by a prefixed id, because the controller decodes it' do
+ product = create(:product, store: store)
+
+ response = dispatcher_for(reader).
+ call(method: :get, path: '/variants', params: { q: { product_id_eq: product.prefixed_id } })
+
+ expect(response).to be_success
+ expect(response.meta['count']).to eq(product.variants.count)
+ expect(response.meta['count']).to be_positive
+ end
+ end
+
+ describe 'the credential' do
+ # Forwarded verbatim, never replaced by an internal header that skips
+ # authentication — that would rebuild the boundary this class removes.
+ it 'is what the API authenticates, so a scope it lacks is refused' do
+ key = create(:api_key, :secret, store: store, scopes: ['read_products'])
+
+ response = dispatcher_for(key).call(method: :post, path: '/products', body: { name: 'No' })
+
+ expect(response.status).to eq(403)
+ expect(response.error_message).to include('write_products')
+ end
+
+ it 'is required: a call carrying none is unauthorized' do
+ response = dispatcher_for(reader, headers: { 'HTTP_HOST' => 'www.example.com' }).
+ call(method: :get, path: '/products')
+
+ expect(response.status).to eq(401)
+ end
+ end
+
+ # `Spree::Current` is a CurrentAttributes, which does not reset for a
+ # request made inside another request. Measured before this class existed:
+ # an inner call overwrote the outer request's currency.
+ describe 'the request state around a dispatch' do
+ it 'leaves the outer request its own store, currency and locale' do
+ Spree::Current.store = store
+ Spree::Current.currency = 'GBP'
+ Spree::Current.locale = 'de'
+
+ dispatcher_for(reader).call(method: :get, path: '/products')
+
+ # Asserted on the stored attributes, not the readers: `currency` falls
+ # back to the store's default, which would agree with 'GBP' only by
+ # luck and hid a broken restore when the snapshot was a shallow dup of
+ # the live hash.
+ expect(Spree::Current.attributes[:currency]).to eq('GBP')
+ expect(Spree::Current.attributes[:locale]).to eq('de')
+ expect(Spree::Current.attributes[:store]).to eq(store)
+ end
+
+ it 'restores the outer state even when the call fails' do
+ Spree::Current.currency = 'GBP'
+
+ dispatcher_for(reader).call(method: :get, path: '/not_a_real_endpoint')
+
+ expect(Spree::Current.attributes[:currency]).to eq('GBP')
+ end
+
+ # The inner request must resolve its own context rather than inherit one,
+ # or a tool call would read whichever store the MCP request was for.
+ it 'does not hand the inner request the outer currency' do
+ Spree::Current.currency = 'GBP'
+
+ response = dispatcher_for(reader).call(method: :get, path: '/products')
+
+ expect(response).to be_success
+ end
+ end
+
+ describe 'a failing call' do
+ it 'carries the API error rather than raising' do
+ response = dispatcher_for(reader).call(method: :get, path: '/products/prod_nope')
+
+ expect(response).not_to be_success
+ expect(response.error_message).to be_present
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools.rb b/spree/core/lib/spree/agent_tools.rb
index 130e16c30b..032bc9a6fc 100644
--- a/spree/core/lib/spree/agent_tools.rb
+++ b/spree/core/lib/spree/agent_tools.rb
@@ -2,6 +2,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/api_dispatch'
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/api_dispatch.rb b/spree/core/lib/spree/agent_tools/api_dispatch.rb
new file mode 100644
index 0000000000..2200c02839
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/api_dispatch.rb
@@ -0,0 +1,135 @@
+module Spree
+ module AgentTools
+ # Runs an Admin API operation for a tool, in this process.
+ #
+ # A tool names an operation; this is what reaches it. The request goes
+ # through the whole stack — routing, authentication, the controller, the
+ # serializer, the error format — so a tool reaches data the way any other
+ # client does, and a guard added to the API protects agents without anyone
+ # copying it here.
+ #
+ # Deliberately not HTTP to itself. A socket back to the same application
+ # holds one web thread waiting on another, so a few concurrent tool calls
+ # on a small pool deadlock the process, and it buys TLS, DNS and timeouts
+ # for nothing.
+ class ApiDispatch
+ # What a dispatched call answers with.
+ Response = Struct.new(:status, :body, :headers, keyword_init: true) do
+ # @return [Boolean]
+ def success?
+ status.between?(200, 299)
+ end
+
+ # The error the API itself rendered, in its own words. A tool repeats
+ # this rather than inventing a message, so a refusal reads the same
+ # however it was reached.
+ #
+ # @return [String, nil]
+ def error_message
+ return if success?
+
+ error = body.is_a?(Hash) ? body['error'] : nil
+ return error if error.is_a?(String)
+ return error['message'] if error.is_a?(Hash) && error['message'].present?
+
+ "The request failed (#{status})."
+ end
+
+ # @return [Hash, Array, nil]
+ def data
+ body.is_a?(Hash) && body.key?('data') ? body['data'] : body
+ end
+
+ # @return [Hash, nil] pagination, when the operation is a listing
+ def meta
+ body['meta'] if body.is_a?(Hash)
+ end
+ end
+
+ # Only what the Admin API reads. Anything else a client sent is the MCP
+ # request's business, not the operation's.
+ FORWARDED_HEADERS = %w[HTTP_AUTHORIZATION HTTP_X_SPREE_API_KEY HTTP_HOST].freeze
+
+ # @param context [Spree::AgentTools::Context]
+ def initialize(context)
+ @context = context
+ end
+
+ # @param method [Symbol] :get, :post, :patch, :delete
+ # @param path [String] the operation's path, already interpolated
+ # @param params [Hash] query parameters for a read
+ # @param body [Hash, nil] the request body for a write
+ # @return [Response]
+ def call(method:, path:, params: {}, body: nil)
+ env = build_env(method, path, params, body)
+
+ # `Spree::Current` is an `ActiveSupport::CurrentAttributes`, which does
+ # NOT reset for a request made inside another request — the executor
+ # is re-entrant. Measured on this branch before this class existed: an
+ # inner call left the outer store in place and overwrote its currency.
+ #
+ # So the outer state is copied, cleared so the inner request resolves
+ # its own from its own headers, and put back whatever happened. The
+ # restore has to sit in this method's own `ensure`: wrapped in a
+ # helper that yields, it ran before the executor finished unwinding
+ # and the outer values were lost again.
+ saved = Spree::Current.attributes.to_a
+ Spree::Current.reset
+
+ begin
+ status, headers, rack_body = Rails.application.call(env)
+ Response.new(status: status, headers: headers, body: parse(rack_body))
+ ensure
+ Spree::Current.reset
+ saved.each { |name, value| Spree::Current.public_send(:"#{name}=", value) }
+ end
+ end
+
+ private
+
+ def build_env(method, path, params, body)
+ query = params.present? ? Rack::Utils.build_nested_query(stringify(params)) : nil
+ payload = body.present? ? JSON.generate(body) : nil
+
+ env = Rack::MockRequest.env_for(
+ [mount_path, path].join,
+ method: method.to_s.upcase,
+ params: query,
+ input: payload,
+ 'CONTENT_TYPE' => ('application/json' if payload)
+ ).compact
+
+ forwarded.each { |name, value| env[name] = value }
+ env['HTTP_ACCEPT'] = 'application/json'
+ env
+ end
+
+ # The credential the caller authenticated with, repeated verbatim. Never
+ # an internal header that skips authentication: that would rebuild the
+ # second security boundary this class exists to remove.
+ def forwarded
+ @context.request_headers.slice(*FORWARDED_HEADERS)
+ end
+
+ def mount_path
+ Spree::Api::Oauth.resources[:admin] if defined?(Spree::Api::Oauth)
+ end
+
+ def parse(rack_body)
+ text = +''
+ rack_body.each { |chunk| text << chunk }
+ rack_body.close if rack_body.respond_to?(:close)
+ return if text.blank?
+
+ JSON.parse(text)
+ rescue JSON::ParserError
+ nil
+ end
+
+ # Rack wants strings; a tool passes whatever the model sent.
+ def stringify(params)
+ params.to_h.deep_transform_keys(&:to_s)
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/agent_tools/context.rb b/spree/core/lib/spree/agent_tools/context.rb
index 60d5a625c9..48606fd6a6 100644
--- a/spree/core/lib/spree/agent_tools/context.rb
+++ b/spree/core/lib/spree/agent_tools/context.rb
@@ -40,13 +40,21 @@ module Spree
# grant carries. They *narrow* the user's own authority and can never
# widen it, so a merchant who consented to reading products does not
# hand over everything their role could do.
- def initialize(store:, user: nil, api_key: nil, ability: nil, granted_scopes: nil)
+ # @return [Hash] the Rack headers the caller authenticated with, which a
+ # dispatched Admin API call repeats verbatim. Empty for a caller that
+ # arrived without a request — a job, a console, a spec — which can
+ # only reach tools that do not dispatch.
+ attr_reader :request_headers
+
+ def initialize(store:, user: nil, api_key: nil, ability: nil, granted_scopes: nil,
+ request_headers: {})
raise ArgumentError, 'Spree::AgentTools::Context needs a user or an api_key' if user.nil? && api_key.nil?
@store = store
@user = user
@api_key = api_key
@granted_scopes = granted_scopes
+ @request_headers = request_headers.to_h
@ability = ability || (Spree::Dependencies.ability_class.constantize.new(user, store: store) if user)
end