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.

Fix: a failed derivation left the resource map permanently empty

Damian Legawiec3b01a12e8073
diff --git a/docs/developer/agentic/admin-mcp.mdx b/docs/developer/agentic/admin-mcp.mdx
index 72b5fe450e..fb3783d23a 100644
--- a/docs/developer/agentic/admin-mcp.mdx
+++ b/docs/developer/agentic/admin-mcp.mdx
@@ -61,7 +61,7 @@ The key travels as a header on every request. Spree accepts it as `X-Spree-API-K
```
</Tab>
<Tab title="Cursor">
- Add to `.cursor/mcp.json` in your project (or `~/.cursor/mcp.json` globally):
+ Add to `~/.cursor/mcp.json` for yourself, or `.cursor/mcp.json` in the project to share it with your team:
```json
{
@@ -73,6 +73,8 @@ The key travels as a header on every request. Spree accepts it as `X-Spree-API-K
}
}
```
+
+ Cursor reads the key from the file, so a project config puts a live credential in your repository. Either keep it in `~/.cursor/mcp.json`, which is outside the project, or add `.cursor/mcp.json` to `.gitignore` and have each developer mint their own key.
</Tab>
<Tab title="VS Code (Copilot)">
Add to `.vscode/mcp.json`. The `inputs` block prompts for the key instead of storing it in the file:
diff --git a/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
index 778483869c..60ae311221 100644
--- a/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
@@ -103,6 +103,27 @@ RSpec.describe 'agent generic record writes' do
end
end
+ # The write tools tell the caller to call describe_resource for the
+ # attributes a resource accepts, so it has to answer that question.
+ describe 'describe_resource and the write tools agree' do
+ it 'lists the attributes a generic write accepts' do
+ described = Spree.agent_tools.available_for(context).
+ find { |candidate| candidate.tool_name == 'describe_resource' }.
+ call(resource: 'markets')[:resources].first
+
+ expect(described[:writable_attributes]).to include('name', 'currency')
+ end
+
+ it 'names the workflow tool for a resource the generic write refuses' do
+ described = Spree.agent_tools.available_for(context).
+ find { |candidate| candidate.tool_name == 'describe_resource' }.
+ call(resource: 'products')[:resources].first
+
+ expect(described[:written_by]).to eq('products_update')
+ expect(described).not_to have_key(:writable_attributes)
+ end
+ end
+
describe 'what a read-only key is offered' do
let(:api_key) { create(:api_key, :secret, store: store, scopes: ['read_all']) }
diff --git a/spree/core/app/tools/spree/agent_tools/describe_resource.rb b/spree/core/app/tools/spree/agent_tools/describe_resource.rb
index e7985e378a..e278faa0b6 100644
--- a/spree/core/app/tools/spree/agent_tools/describe_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/describe_resource.rb
@@ -30,17 +30,31 @@ module Spree
private
+ def writable_attributes_for(entry)
+ return unless entry.generic_writes?
+ return unless context.permitted?(entry.write_permission)
+
+ entry.writable_attribute_names.presence
+ end
+
def describe(entry)
{
resource: entry.key,
filterable_fields: entry.filterable_fields,
+ # What a generic write accepts, so the model learns the schema here
+ # rather than by sending an invalid write and reading the refusal —
+ # which is what create_resource and update_resource tell it to do.
+ # Offered only where the caller could actually write.
+ writable_attributes: writable_attributes_for(entry),
+ # Named so a model that reaches for a write knows which tool does it.
+ written_by: (entry.update_workflow_key || entry.create_workflow_key)&.tr('.', '_'),
# Named queries answer things no column can — stock levels live
# across warehouses, so "out of stock" is a scope, not a field.
filterable_scopes: entry.filterable_scopes,
usage: 'Attribute filters use Ransack predicates, e.g. name_cont, created_at_gteq, ' \
'status_eq. Named scopes are passed as a bare key set to true, e.g. ' \
'{"out_of_stock": true}.'
- }
+ }.compact
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/get_import_status.rb b/spree/core/app/tools/spree/agent_tools/get_import_status.rb
index 4467d403ff..74d433be0b 100644
--- a/spree/core/app/tools/spree/agent_tools/get_import_status.rb
+++ b/spree/core/app/tools/spree/agent_tools/get_import_status.rb
@@ -6,6 +6,8 @@ module Spree
# why did those rows fail? Both are tedious to assemble from the imports
# page and easy to say in a sentence.
class GetImportStatus < Spree::AgentTools::ImportTool
+ # How many failed rows are read to work out why they failed.
+ SCANNED_ROW_LIMIT = 200
FAILED_ROW_SAMPLE = 5
tool_name 'get_import_status'
@@ -45,15 +47,23 @@ module Spree
# Grouped so the assistant can say "12 rows failed because the SKU was
# missing" rather than reciting every row.
+ #
+ # Counted over a sample rather than the whole failure set, because an
+ # import that failed wholesale has as many rows as the file did. The
+ # counts therefore say `rows_in_sample`, not `rows`: reporting a sample
+ # as a total would have the assistant tell the merchant twelve rows
+ # failed when twelve hundred did.
def failure_reasons(import)
- failed = import.rows.failed.limit(200)
+ failed = import.rows.failed.limit(SCANNED_ROW_LIMIT).to_a
return if failed.empty?
- failed.filter_map { |row| row.validation_errors.presence }
- .tally
- .sort_by { |_reason, count| -count }
- .first(FAILED_ROW_SAMPLE)
- .map { |reason, count| { reason: reason, rows: count } }
+ reasons = failed.filter_map { |row| row.validation_errors.presence }
+ .tally
+ .sort_by { |_reason, count| -count }
+ .first(FAILED_ROW_SAMPLE)
+ .map { |reason, count| { reason: reason, rows_in_sample: count } }
+
+ { scanned: failed.size, total_failed: import.rows.failed.count, reasons: reasons }
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/get_resource.rb b/spree/core/app/tools/spree/agent_tools/get_resource.rb
index 33ffcbd50a..37d5496ebe 100644
--- a/spree/core/app/tools/spree/agent_tools/get_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/get_resource.rb
@@ -19,6 +19,9 @@ module Spree
return { error: "No #{entry.key.singularize} found for #{id.inspect}" } if record.nil?
attributes = serialize(entry, record)
+ # An empty hash would be reported as a successful lookup of a record
+ # with no fields, which is worse than saying the read failed.
+ return { error: "Could not read this #{entry.key.singularize}." } if attributes.nil?
{
resource: entry.key,
@@ -58,7 +61,7 @@ module Spree
Spree::AgentTools::RecordSummary.sanitize(entry.serializer_class.new(record).to_h)
rescue StandardError => e
Rails.logger.warn("[Spree] #{entry.key} serializer failed: #{e.class}: #{e.message}")
- {}
+ nil
end
# Scoped through the store, so an id belonging to another store is a
diff --git a/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb b/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb
index c444d79bc9..ca29cc8c99 100644
--- a/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb
+++ b/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb
@@ -46,6 +46,13 @@ module Spree
pairs = sanitize(import, mapping)
return unknown_fields(import, mapping) if pairs.empty?
+ # A pair naming a field or column that does not exist is dropped here
+ # rather than refusing the whole proposal — the valid half is usually
+ # most of it, and a model that misspelled one heading should not have
+ # to resend forty. It is named back, so the model can correct that one
+ # and never believes it was applied.
+ rejected = mapping.to_h.keys.map(&:to_s) - pairs.keys
+
applied = apply!(import, pairs)
start_if_ready(import)
@@ -56,6 +63,10 @@ module Spree
# its mapping row did not exist would have the model tell the
# merchant a column was handled when it was not.
mapped: applied,
+ # Named back so the model knows exactly what did not land, and why:
+ # `rejected` did not exist on this import, `unmapped` exists but has
+ # no mapping row to write to.
+ rejected: rejected.presence,
unmapped: (pairs.keys - applied.keys).presence,
status: import.reload.status,
# `mapped_fields` returns mapping records, not names.
diff --git a/spree/core/lib/spree/agent_tools/resource_map.rb b/spree/core/lib/spree/agent_tools/resource_map.rb
index 9cdbd33efd..1a45cbb02f 100644
--- a/spree/core/lib/spree/agent_tools/resource_map.rb
+++ b/spree/core/lib/spree/agent_tools/resource_map.rb
@@ -195,14 +195,33 @@ module Spree
# Fills the map once, from whatever `deriver` was registered.
#
+ # Under a mutex, because the deriver rebuilds in place — it clears the
+ # map and registers each entry — so a second thread reading between
+ # those two moments would see an empty map and report every resource
+ # as unknown.
+ #
+ # The flag is cleared again if the deriver raises: the map is empty by
+ # then, and leaving it marked derived would answer "unknown resource"
+ # for the rest of the process, since `stale!` only runs at boot and on
+ # reload. A failed derivation is retried by the next caller instead.
+ #
# @return [void]
def derive!
return if @derived || deriver.nil?
- # Set before calling, so a deriver that reads the map while filling
- # it does not recurse.
- @derived = true
- deriver.call
+ derive_mutex.synchronize do
+ return if @derived
+
+ # Set before calling, so a deriver that reads the map while filling
+ # it does not recurse.
+ @derived = true
+ begin
+ deriver.call
+ rescue StandardError
+ @derived = false
+ raise
+ end
+ end
end
# Resources this caller may read, so a tool description lists only what
@@ -219,6 +238,10 @@ module Spree
def entries
@entries ||= {}
end
+
+ def derive_mutex
+ @derive_mutex ||= Mutex.new
+ end
end
end
end