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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Document how an extension adds a tool, and refuse an unknown resource the same way everywhere
Damian Legawiec23c716c06513
diff --git a/docs/developer/agentic/admin-mcp.mdx b/docs/developer/agentic/admin-mcp.mdxindex fb3783d23a..e093c4a8d1 100644--- a/docs/developer/agentic/admin-mcp.mdx+++ b/docs/developer/agentic/admin-mcp.mdx@@ -144,6 +144,56 @@ Some things are deliberately out of reach, whatever scopes the key holds.- **Files.** Media uploads, import files and label downloads. The protocol carries text and structured data.- **Order editing.** Adding line items, discounts and fees to an existing order still runs through paths that are not yet workflows. Cancelling, refunding and fulfilling all work today.+## Adding your own tools++The catalog is a registry in `spree_core`, so an extension or a host application adds to it without depending on the MCP gem. Two kinds of thing to add.++**A back-office operation you already have as a workflow.** Name its `Spree::Dependencies` key and the permission that should gate it:++```ruby server/config/initializers/spree.rb+Spree.agent_tools.expose_workflows(supplier_sync_workflow: 'write_purchasing')+```++That is the whole change. The tool's name comes from the workflow's own key (`suppliers.sync` becomes `suppliers_sync`), its description from the class's leading comment, and its parameters from `perform`'s signature and the YARD `@param` lines above it — so the tool and the workflow cannot drift apart. Two rules the derivation relies on: every parameter needs an `@param` with a type, and a parameter naming a record must be typed as a model the agent can already read.++**Something that is not a workflow** — a lookup against another system, a report of your own. Subclass `Spree::AgentTool` and register the class by name:++```ruby app/tools/my_shop/agent_tools/supplier_stock.rb+module MyShop+ module AgentTools+ # Asks the supplier's API what they hold, so a merchant can ask before+ # committing to a purchase order.+ class SupplierStock < Spree::AgentTool+ tool_name 'supplier_stock'+ description 'Current stock at a supplier, by SKU.'+ permission 'read_purchasing'++ param :sku, description: 'The SKU to look up', required: true++ def call(sku:)+ stock = MyShop::SupplierApi.stock_for(sku, store: context.store)+ return { error: "No supplier carries #{sku}." } if stock.nil?++ { summary: "#{sku}: #{stock} available", sku: sku, available: stock }+ end+ end+ end+end+```++```ruby server/config/initializers/spree.rb+Spree.agent_tools << 'MyShop::AgentTools::SupplierStock'+```++Four things worth knowing when you write one:++- **Registration is by name, not by class**, so your edits to a description or a parameter take effect on the next request rather than needing a restart.+- **`context` is who is asking**: `context.store` is always the caller's store, and `context.principal` is the admin or the API key — pass it to anything that records who acted.+- **A refusal is `{ error: '…' }`**, not an exception. The model reads that text and corrects itself, so write it as an instruction rather than a stack trace.+- **Keep the result small.** It lands in the model's context. Return a `summary` line plus the few fields that answer the question, and let the caller ask for more.++A tool is offered only to a credential holding its `permission`, so a key that cannot read purchasing never learns `supplier_stock` exists.+## Choosing between this and the CLIIf your agent has a shell, the [`spree api` CLI](/developer/cli/admin-api) is usually the better tool: it reaches every endpoint, handles bulk work, and its output can be piped into other commands. This server is for agents that cannot shell out, and for conversational work where a job-shaped tool beats composing raw HTTP calls.diff --git a/docs/plans/6.0-mcp-server.md b/docs/plans/6.0-mcp-server.mdindex a085f847bc..fb8d944945 100644--- a/docs/plans/6.0-mcp-server.md+++ b/docs/plans/6.0-mcp-server.md@@ -701,7 +701,19 @@ and any later adapter inherit them rather than rediscovering them:- **Keep `admin.yaml` regenerated after Admin API changes**; the writableschemas `describe_resource` returns come from it.- **Keep tool results compact.** A tool that returns a full admin payload by- default is a defect: results land in the model's context.+ default is a defect: results land in the model's context. For the same reason a+ result is never sent twice: the payload travels as structured content, and+ the text half carries a summary line, not a second copy of it.+- **A credential is not always under a credential-shaped key.** The outbound+ filter matches key names (`token`, `secret`, `password`) *and* values,+ because several serializers expose a link whose own path or query string is+ the secret — an invitation's `acceptance_url` mints a staff account, a+ digital link's `download_url` is the customer's file, and the endpoints both+ address authenticate on the link alone. A new attribute of that shape goes+ in `RecordSummary::SECRET_ATTRIBUTES`, or its model in `WITHHELD_MODELS`; a+ contract spec fails when a registered resource emits its own record's secure+ token. Arrays are filtered element by element, because tags are+ caller-controlled and serialize as a bare string array.## Open Questionsdiff --git a/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rb b/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rbnew file mode 100644index 0000000000..8e1d3fe357--- /dev/null+++ b/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rb@@ -0,0 +1,48 @@+require 'spec_helper'++# The registry is a public extension point, and+# docs/developer/agentic/admin-mcp.mdx tells an author to write exactly this+# tool. Documentation that does not compile is worse than none, so the example+# is pinned here — change one and this fails until the other follows.+RSpec.describe 'the extension path the docs describe' do+ let(:store) { @default_store }+ let(:key) { create(:api_key, :secret, store: store, scopes: ['read_purchasing']) }+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: key) }++ before do+ stub_const('MyShop', Module.new)+ stub_const('MyShop::AgentTools', Module.new)+ stub_const('MyShop::AgentTools::SupplierStock', Class.new(Spree::AgentTool) do+ tool_name 'supplier_stock'+ description 'Current stock at a supplier, by SKU.'+ permission 'read_purchasing'+ param :sku, description: 'The SKU to look up', required: true++ def call(sku:)+ stock = { 'BS-1' => 42 }[sku]+ return { error: "No supplier carries #{sku}." } if stock.nil?++ { summary: "#{sku}: #{stock} available", sku: sku, available: stock }+ end+ end)+ Spree.agent_tools << 'MyShop::AgentTools::SupplierStock'+ end++ it 'is offered to a key holding the permission' do+ names = Spree.agent_tools.available_for(context).map(&:tool_name)+ expect(names).to include('supplier_stock')+ end++ it 'answers and refuses as documented' do+ tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'supplier_stock' }+ expect(tool.call(sku: 'BS-1')[:summary]).to eq('BS-1: 42 available')+ expect(tool.call(sku: 'NOPE')[:error]).to include('NOPE')+ end++ it 'is hidden from a key without the permission' do+ other = create(:api_key, :secret, store: store, scopes: ['read_products'])+ ctx = Spree::AgentTools::Context.new(store: store, api_key: other)++ expect(Spree.agent_tools.available_for(ctx).map(&:tool_name)).not_to include('supplier_stock')+ end+enddiff --git a/spree/core/app/tools/spree/agent_tools/get_resource.rb b/spree/core/app/tools/spree/agent_tools/get_resource.rbindex 37d5496ebe..131d01d577 100644--- a/spree/core/app/tools/spree/agent_tools/get_resource.rb+++ b/spree/core/app/tools/spree/agent_tools/get_resource.rb@@ -12,7 +12,7 @@ module Spreedef call(resource:, id:)entry = Spree::AgentTools::ResourceMap.find(resource)- return { error: "Unknown resource #{resource.inspect}" } if entry.nil?+ return unknown_resource(resource) if entry.nil?return { error: "You do not have permission to read #{entry.key}." } unless context.permitted?(entry.permission)record = find_record(entry, id)diff --git a/spree/core/app/tools/spree/agent_tools/resource_write.rb b/spree/core/app/tools/spree/agent_tools/resource_write.rbindex b377027e2c..5d6b231290 100644--- a/spree/core/app/tools/spree/agent_tools/resource_write.rb+++ b/spree/core/app/tools/spree/agent_tools/resource_write.rb@@ -35,7 +35,7 @@ module Spree# @return [Array(ResourceMap::Entry, nil), Array(nil, Hash)]def writable_entry(key)entry = ResourceMap.find(key)- return [nil, { error: "Unknown resource #{key.inspect}." }] if entry.nil?+ return [nil, unknown_resource(key)] if entry.nil?unless entry.generic_writes?return [nil, { error: refusal_for(entry) }]diff --git a/spree/core/app/tools/spree/agent_tools/search_resources.rb b/spree/core/app/tools/spree/agent_tools/search_resources.rbindex 7bbaa5900e..025a885b9d 100644--- a/spree/core/app/tools/spree/agent_tools/search_resources.rb+++ b/spree/core/app/tools/spree/agent_tools/search_resources.rb@@ -139,13 +139,6 @@ module Spree[[limit.to_i, 1].max, MAX_LIMIT].minend- def unknown_resource(resource)- {- error: "Unknown resource #{resource.inspect}",- available: Spree::AgentTools::ResourceMap.available_for(context).map(&:key)- }- end-def forbidden(entry){ error: "You do not have permission to read #{entry.key}." }enddiff --git a/spree/core/lib/spree/agent_tool.rb b/spree/core/lib/spree/agent_tool.rbindex 80d1b236f2..5500423a08 100644--- a/spree/core/lib/spree/agent_tool.rb+++ b/spree/core/lib/spree/agent_tool.rb@@ -132,6 +132,22 @@ class AgentToolcontext.permitted?(permission)end+ # A resource the map does not hold, answered with the ones it does.+ #+ # Every tool that takes a resource key refuses the same way: naming what is+ # available is what lets the model correct itself in one step instead of+ # guessing again, and a caller only ever sees resources its own credential+ # may read.+ #+ # @param key [String]+ # @return [Hash]+ def unknown_resource(key)+ {+ error: "Unknown resource #{key.to_s.inspect}. Call describe_resource for the list.",+ available: Spree::AgentTools::ResourceMap.available_for(context).map(&:key)+ }+ end+protected# Refuses unless this admin may take `action` on `record`.