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
Fix: reporting measured a delegated credential against its owner's role
Damian Legawiec7b58d6e0b493
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex be791885d0..4e1d16c3aa 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -54542,6 +54542,94 @@ paths:responses:'204':description: supplier deleted+<<<<<<< HEAD+=======+ "/api/v3/oauth/protected-resource/{resource_key}":+ parameters:+ - name: resource_key+ in: path+ required: true+ description: Which protected surface, e.g. `mcp`+ schema:+ type: string+ get:+ summary: Discover the authorization server+ tags:+ - OAuth+ description: |+ RFC 9728. A client given a URL it cannot reach unauthenticated reads+ this to learn which authorization server guards it and which+ permissions that server accepts.++ Unauthenticated by design: a client has to read it before it holds+ anything.+ responses:+ '200':+ description: metadata+ content:+ application/json:+ example:+ resource: http://www.example.com/api/v3/admin/mcp+ authorization_servers:+ - http://www.example.com+ scopes_supported:+ - read_dashboard+ - read_reports+ - write_reports+ - read_orders+ - write_orders+ - read_payments+ - write_payments+ - read_fulfillments+ - write_fulfillments+ - read_refunds+ - write_refunds+ - read_products+ - write_products+ - read_product_types+ - write_product_types+ - read_publishing+ - write_publishing+ - read_media+ - write_media+ - read_categories+ - write_categories+ - read_collections+ - write_collections+ - read_stock+ - write_stock+ - read_purchasing+ - write_purchasing+ - read_customers+ - write_customers+ - read_sellers+ - write_sellers+ - read_commissions+ - write_commissions+ - read_payouts+ - write_payouts+ - read_gift_cards+ - write_gift_cards+ - read_store_credits+ - write_store_credits+ - read_promotions+ - write_promotions+ - read_settings+ - write_settings+ - read_delivery_methods+ - write_delivery_methods+ - read_package_types+ - write_package_types+ - read_email_templates+ - write_email_templates+ bearer_methods_supported:+ - header+ resource_documentation: https://spreecommerce.org/docs/developer/mcp/overview+ schema:+ "$ref": "#/components/schemas/OauthProtectedResource"+ '404':+ description: no such protected surface+>>>>>>> a2726dc670 (Changed the MCP docs into a section of their own)servers:- url: http://{defaultHost}variables:diff --git a/docs/developer/agentic/admin-mcp.mdx b/docs/developer/agentic/admin-mcp.mdxdeleted file mode 100644index dfc77cbe66..0000000000--- a/docs/developer/agentic/admin-mcp.mdx+++ /dev/null@@ -1,148 +0,0 @@-----title: "Admin MCP Server"-sidebarTitle: Admin MCP-description: "Let Claude, Cursor or your own agent merchandise the catalog, answer reporting questions and manage store setup in plain language, under the same permissions as the Admin API."------Your store can host a [Model Context Protocol](https://modelcontextprotocol.io) server of its own. Where the [docs MCP server](/developer/agentic/mcp) lets an agent read Spree's documentation, this one lets an agent operate *your* store: find products, answer "what did we sell in Germany last month", cancel an order, mark a shipment delivered, add a market.--It runs inside your Spree application — there is no separate service to deploy — and a request goes through the same tenancy, permission and validation rules as the Admin API. An agent can do exactly what the credential you give it allows, and nothing else.--```text-https://your-store.com/api/v3/admin/mcp-```--<Note>- The server is an optional gem. Add `spree_mcp` to your `Gemfile` and restart; there is nothing else to configure.-- ```ruby server/Gemfile- gem 'spree_mcp'- ```-</Note>--## Connecting--Paste your store's MCP URL into the client. It will send you to Spree, where you sign in and approve what the agent may do.--```text-https://your-store.com/api/v3/admin/mcp-```--That is the whole setup — there is no key to mint or paste. Every MCP client works this way: Claude Code, Cursor, VS Code, claude.ai, Claude Desktop, ChatGPT and anything else implementing the protocol's authorization.--What you approve matters more than it looks:--- **An agent never gets more than you have.** The grant narrows your own permissions, so a staff member who cannot issue refunds cannot approve an agent that can.-- **Only what you approved.** Approving product access does not quietly include orders — the tools for anything else are not even offered.-- **It is yours, not the store's.** Each person connects for themselves, so an agent's actions are recorded against whoever approved it.-- **Revoke whenever you like.** **Settings → Connected apps** lists everything connected, who approved it and when each was last used. Revoking stops it on the next call.--<Note>- A Spree API key is not accepted here, and that is deliberate: an agent acts for a person, so it carries that person's own permissions rather than a standing credential with nobody behind it. For scripted access that cannot sign in — a CI job, a server-side integration — use the [`spree api` CLI](/developer/cli/admin-api), which is what API keys are for.-</Note>--## What the agent can do--The tools are not a mirror of the API's endpoints — there would be hundreds, and a catalog that size makes a model worse at choosing. They come in four groups instead.--| Group | Tools | What they are for |-| --- | --- | --- |-| Finding things | `describe_resource`, `search_resources`, `get_resource` | Discovering which resources exist and what they can be filtered by, then finding and reading records |-| Answering with numbers | `describe_reporting`, `query_report` | Revenue, orders and units, sliced by time, product, channel or country — the same figures the dashboard charts show |-| Doing things | One tool per operation: `orders_create`, `orders_cancel`, `fulfillments_mark_delivered`, `products_activate`, `refunds_create`, `price_lists_activate` and around fifty more | Each runs the same workflow the dashboard runs, so validations, emails and webhooks behave identically |-| Merchandising | `curate_products` | Which products a category, collection, catalog or price list holds |-| Receiving files | `upload_file`, then `media_create`, `create_import` or an update | A merchant hands over an image, a CSV or a buyer's purchase order: store the file, then put it in a product gallery, start an import from it, or set it on the order |-| Reading files | MCP resources | Finished exports, as CSV |-| Store setup | `create_resource`, `update_resource`, `delete_resource` | Markets, channels, delivery and payment methods, tax rates and the rest of the settings screens |--An agent is only ever shown the tools its key permits, so the list stays small and relevant: a key minted for order operations sees around twenty.--### How a conversation goes--The agent picks tools from what you ask; there is no command to learn.--> **You:** Which products are out of stock, and what did we sell in Germany last month?--The agent calls `describe_resource` to learn that products can be filtered by an `out_of_stock` scope, `search_resources` to list them, then `describe_reporting` and `query_report` for the German figures — and answers in one reply.--> **You:** Cancel order R123456789, refund the customer, and tell them why.--The agent finds the order, then calls `orders_cancel`. Your client asks you to confirm before the call runs; Spree then runs the same cancellation the dashboard runs, and the order's timeline records the API key as the canceller, so an audit later shows which agent did it.--## What it will not do--Some things are deliberately out of reach, whatever scopes the key holds.--- **Credentials.** API keys, integrations, webhook endpoints and gift card codes are never returned by any tool. A gift card code is the money itself, and an integration's settings are where provider credentials live.-- **Erasing a customer.** GDPR erasure is irreversible and is not something to put behind a single confirmation prompt. Do it in the dashboard.-- **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 CLI--The two surfaces take different credentials, and the difference is the point: **this server takes a person's approval, the CLI takes an API key.**--| | Admin MCP | [`spree api` CLI](/developer/cli/admin-api) |-| --- | --- | --- |-| Credential | Sign in and approve | A secret API key |-| Suits | An agent acting for someone, conversationally | Scripts, CI, bulk work, anything without a browser |-| Reach | The tools listed above | Every endpoint |-| Actions recorded against | The person who approved | The key |--Reach for the CLI when the work is scripted or needs the full API. Reach for this server when an agent is doing the work on someone's behalf — a tool shaped like "cancel this order" gives a model far less room to go wrong than composing the HTTP call itself, and each one runs the same workflow the dashboard runs.--## See also--- [Docs MCP server](/developer/agentic/mcp) — the same protocol, for reading Spree's documentation-- [Agent skills](/developer/agentic/agent-skills) — teaching an agent how your team works with Spree-- [API keys and scopes](/user/settings/api-keys) — minting a key and what each scope grants-- [Permissions](/developer/customization/permissions) — the catalog the scopes come fromdiff --git a/docs/developer/agentic/mcp.mdx b/docs/developer/agentic/mcp.mdxindex d5ea1c6819..f67f58303f 100644--- a/docs/developer/agentic/mcp.mdx+++ b/docs/developer/agentic/mcp.mdx@@ -15,7 +15,7 @@ The server exposes two tools: full-text **search** across the documentation, and<Note>This server is about Spree's documentation, not your store. To let an agentwork on your own catalog, orders and settings, see the- [Admin MCP server](/developer/agentic/admin-mcp) — the same protocol, hosted+ [Admin MCP server](/developer/mcp/overview) — the same protocol, hostedby your application and authenticated with one of your API keys.</Note>@@ -86,7 +86,7 @@ To connect a single tool by hand, or one outside a create-spree-app project:| **MCP server** (this page) | The latest published docs; agents working outside a scaffolded project; questions the installed skills don't cover || **[`@spree/docs` npm package](/developer/agentic/llm-docs)** | Fast local reads inside a project — no network round-trip, works offline, pinned to what you installed || **[Agent skills](/developer/agentic/agent-skills)** | Conventions and how-to knowledge the agent should apply without searching at all |-| **[Admin MCP server](/developer/agentic/admin-mcp)** | Not docs at all — operating a real store: its catalog, orders, reports and settings |+| **[Admin MCP server](/developer/mcp/overview)** | Not docs at all — operating a real store: its catalog, orders, reports and settings |<Note>New [create-spree-app](/developer/create-spree-app/quickstart) projects come connected (skip it with `--no-docs-mcp`) — Claude Code asks you to approve the server the first time you open the project. The project's `AGENTS.md` tells agents to search here and read pages from the local `@spree/docs` package, which matches the Spree version the project runs.diff --git a/docs/developer/agentic/overview.mdx b/docs/developer/agentic/overview.mdxindex 1bacb939bb..72dad3bbf7 100644--- a/docs/developer/agentic/overview.mdx+++ b/docs/developer/agentic/overview.mdx@@ -22,7 +22,7 @@ Spree ships first-class tooling for AI-assisted development. Whether you use Cla<Card title="Docs MCP Server" icon="plug" href="/developer/agentic/mcp">Connect your agent to the Spree documentation MCP server to search and read the latest docs while building.</Card>- <Card title="Admin MCP Server" icon="store" href="/developer/agentic/admin-mcp">+ <Card title="Admin MCP Server" icon="store" href="/developer/mcp/overview">Let an agent run your store — merchandise the catalog, answer reporting questions, manage orders and setup — under the same permissions as the Admin API.</Card><Card title="LLM-Ready Docs" icon="file-text" href="/developer/agentic/llm-docs">diff --git a/docs/developer/mcp/custom-tools.mdx b/docs/developer/mcp/custom-tools.mdxnew file mode 100644index 0000000000..3e231f6b4c--- /dev/null+++ b/docs/developer/mcp/custom-tools.mdx@@ -0,0 +1,83 @@+---+title: "Custom Tools"+sidebarTitle: Custom tools+description: "Add your own tools to the MCP server, or expose a workflow your extension already ships."+---++The catalog is a registry in `spree_core`, so an extension or a host application adds to it without depending on the MCP gem. Anything registered is offered to the admin MCP server and to any other adapter reading the same registry.++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.admin_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.admin_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.++## Which registry++There is one registry per surface, named the way the authentication strategies are:++```ruby+Spree.admin_agent_tools # the back office+Spree.store_agent_tools # the storefront (no catalog yet)+```++A tool declares the surface it belongs to, defaulting to `:admin`, so registering one in the wrong place raises rather than being discovered when a storefront visitor is offered the back office:++```ruby+class SupplierStock < Spree::AgentTool+ audience :admin # the default; state it when a tool is storefront-facing+end+```++## See also++<CardGroup cols={2}>+ <Card title="Tool reference" icon="wrench" href="/developer/mcp/tools">+ The tools that ship, and the shape yours should follow.+ </Card>+ <Card title="Workflows" icon="diagram-project" href="/developer/customization/workflows">+ What `expose_workflows` is exposing.+ </Card>+</CardGroup>diff --git a/docs/developer/mcp/overview.mdx b/docs/developer/mcp/overview.mdxnew file mode 100644index 0000000000..0fcf86b095--- /dev/null+++ b/docs/developer/mcp/overview.mdx@@ -0,0 +1,59 @@+---+title: "MCP Server"+sidebarTitle: Overview+description: "Your store hosts a Model Context Protocol server, so an AI client can operate it in plain language under the same permissions as the API."+---++Spree can host a [Model Context Protocol](https://modelcontextprotocol.io) server of its own, so an MCP client — Claude Desktop, claude.ai, Claude Code, Cursor, an in-house agent — can work in your store by talking to it: find products, answer "what did we sell in Germany last month", cancel an order, mark a shipment delivered, add a market.++It runs inside your Spree application. There is no separate service to deploy, and every request goes through the same tenancy, permission and validation rules as the API itself. An agent does exactly what the person who connected it allows, and nothing else.++## The endpoint++```text+https://your-store.com/api/v3/admin/mcp+```++The back office: the catalog, orders, reporting and store setup, for staff and the agents they connect.++<Note>+ A storefront endpoint, for agents acting on a customer's behalf, is not built yet. The machinery is shared and the catalogs are separate, so it arrives as an addition rather than a rework — see [what is not here yet](#what-is-not-here-yet).+</Note>++## How it fits together++An MCP client speaks JSON-RPC to one endpoint. Behind it:++- **Tools** are what the agent can do — one per operation, named for the merchant's language rather than the API's. [The reference](/developer/mcp/tools) lists all 58.+- **Resources** are files the client can fetch. Finished exports, as CSV.+- **Consent** decides what any of it reaches. A merchant signs in and approves specific permissions; the agent is never offered a tool outside them.++Every tool reaches data by making a real API request inside the process — the same routing, authentication, record-level authorization and serialization an external client gets. A guard added to the API protects agents without anyone copying it into the tool layer.++## Getting started++<CardGroup cols={2}>+ <Card title="Quick start" icon="rocket" href="/developer/mcp/quick-start">+ Install the gem, connect a client, run the first conversation.+ </Card>+ <Card title="Tool reference" icon="wrench" href="/developer/mcp/tools">+ All 58 tools, what each is for and which permission it needs.+ </Card>+ <Card title="Permissions and consent" icon="shield-check" href="/developer/mcp/permissions">+ What a merchant approves, how a grant is bounded, revoking access.+ </Card>+ <Card title="Custom tools" icon="puzzle-piece" href="/developer/mcp/custom-tools">+ Register your own, and expose a workflow an extension adds.+ </Card>+</CardGroup>++## What it is not++**Not the documentation server.** The [docs MCP server](/developer/agentic/mcp) lets an agent read Spree's documentation while writing code against it. This one operates a live store. They are unrelated and you can use both.++**Not a replacement for the API.** An agent is good at a merchant's request in words. A scheduled job, a data pipeline or a storefront should call the [Admin API](/api-reference/admin) or the [`spree api` CLI](/developer/cli/admin-api) directly.++## What is not here yet++- **A storefront endpoint.** Tools for a customer-facing agent — browsing, carts, order status — need a customer principal and their own catalog.+- **Product status moves.** Activating, drafting and archiving a product run inside the Spree process rather than through an endpoint, because the Admin API has none for them yet.diff --git a/docs/developer/mcp/permissions.mdx b/docs/developer/mcp/permissions.mdxnew file mode 100644index 0000000000..2a1ebd1cc1--- /dev/null+++ b/docs/developer/mcp/permissions.mdx@@ -0,0 +1,60 @@+---+title: "Permissions and Consent"+sidebarTitle: Permissions+description: "What a merchant approves when they connect an agent, how a grant is bounded, and how to take it away."+---++An agent acts for the person who connected it. There is no standing credential with nobody behind it, and no key to rotate — the merchant signs in, approves specific permissions, and those permissions are the ceiling for everything that follows.++## What a merchant approves++Connecting sends the merchant to Spree, where a consent screen lists the permissions the client asked for and lets them tick the ones to hand over. The vocabulary is the same as a staff role's — `read_products`, `write_orders` — so a grant is expressed in terms the merchant already understands from the dashboard.++Three rules bound it:++**A grant can only narrow.** It is the intersection of what the client asked for and what the approver holds. A staff member who cannot issue refunds cannot approve an agent that can, and a request naming a permission they lack is cut down rather than honoured.++**It is a standing ceiling, not a one-off.** The grant persists until revoked, which is why it is recorded as the intersection rather than as what was asked for. Recorded too wide, it would widen on its own the day that person is promoted.++**It is per person.** Each staff member connects for themselves, so an agent's actions are recorded against whoever approved it, and **Settings → Connected apps** shows each person their own connections.++## What a grant can never hold++Some permissions are never offered on the consent screen, whatever the client asks for: API keys, integrations, webhook endpoints, roles and staff accounts.++These are the permissions that mint *other* credentials. If a grant could hold them, an agent could create an API key with wider scopes than its own, and the ceiling would mean nothing.++## How the ceiling is enforced++A grant narrows at two points, and both matter:++**Which tools are offered.** The model is never shown a tool outside the grant, so it does not try and fail — it has no way to ask.++**What each call reaches.** Tool visibility is per permission; the data behind it is checked per resource and per record. A connection granted `read_reports` can run a report, and is still refused a dimension exposing customers unless it also holds `read_customers`.++The second matters because the first is about what the model knows, not about what the store allows. Every tool reaches data by making a real API request with the grant's own credential, so a host application's record-level rules — `can :manage, Spree::Product, seller_id: …` — narrow an agent exactly as they narrow a person.++## Revoking++**Settings → Connected apps** lists everything connected, who approved it and when each was last used. Revoking takes effect on the agent's next call: it revokes every live token and grant rather than deleting the registration, so a client that still holds a token stops working immediately and the merchant can reconnect later without re-registering.++## Registering a client++A client is registered once per store, under **Settings → OAuth clients**, before any merchant connects it. A registration carries no permissions of its own — what a client may do is decided per merchant at consent.++Clients are public rather than confidential: a hosted connector cannot keep a secret, so PKCE is required instead of a client secret.++## For integrations that cannot sign in++A CI job, a nightly sync or a server-side integration has no person behind it and no browser to sign in with. Those use a [secret API key](/developer/cli/admin-api) with its own scopes, which is what API keys are for. The MCP endpoint deliberately refuses them.++## See also++<CardGroup cols={2}>+ <Card title="Tool reference" icon="wrench" href="/developer/mcp/tools">+ Which permission each tool needs.+ </Card>+ <Card title="Roles and permissions" icon="users" href="/developer/customization/permissions">+ The permission catalog a grant draws from.+ </Card>+</CardGroup>diff --git a/docs/developer/mcp/quick-start.mdx b/docs/developer/mcp/quick-start.mdxnew file mode 100644index 0000000000..e38688fe36--- /dev/null+++ b/docs/developer/mcp/quick-start.mdx@@ -0,0 +1,147 @@+---+title: "Quick Start"+sidebarTitle: Quick start+description: "Install the MCP server, connect an AI client and run the first conversation against your store."+---++## Install the gem++The server ships as an optional gem. Add it and restart; there is nothing to configure.++<Tabs>+ <Tab title="Spree CLI">+ ```bash+ spree add mcp+ ```+ </Tab>+ <Tab title="Without CLI">+ ```ruby server/Gemfile+ gem 'spree_mcp'+ ```++ ```bash+ bundle install+ ```+ </Tab>+</Tabs>++The endpoint is then live:++```text+https://your-store.com/api/v3/admin/mcp+```++No migration is needed for the server itself. OAuth tables ship with `spree_core` and are installed with Spree's other migrations.++## Connect a client++Paste the URL into your MCP client. It sends you to Spree, you sign in, and you approve what the agent may do.++<Tabs>+ <Tab title="Claude Code">+ ```bash+ claude mcp add --transport http spree https://your-store.com/api/v3/admin/mcp+ ```+ </Tab>+ <Tab title="Claude Desktop / claude.ai">+ **Settings → Connectors → Add custom connector**, then paste the URL.+ </Tab>+ <Tab title="Cursor">+ ```json .cursor/mcp.json+ {+ "mcpServers": {+ "spree": {+ "url": "https://your-store.com/api/v3/admin/mcp"+ }+ }+ }+ ```+ </Tab>+ <Tab title="VS Code">+ ```json .vscode/mcp.json+ {+ "servers": {+ "spree": {+ "type": "http",+ "url": "https://your-store.com/api/v3/admin/mcp"+ }+ }+ }+ ```+ </Tab>+</Tabs>++That is the whole setup. There is no key to mint, paste or rotate — the client discovers how to authorize itself from the endpoint, and you approve it in a browser.++<Note>+ A Spree API key is **not** accepted here, deliberately: an agent acts for a person, so it carries that person's own permissions rather than a standing credential with nobody behind it. For access that cannot sign in — a CI job, a server-side integration — use the [`spree api` CLI](/developer/cli/admin-api).+</Note>++## Approve what it may do++Signing in brings up a consent screen listing the permissions the client asked for. Tick the ones you want it to have.++What you approve matters more than it looks:++- **An agent never gets more than you have.** The grant narrows your own permissions, so a staff member who cannot issue refunds cannot approve an agent that can.+- **Only what you approved.** Approving product access does not quietly include orders — the tools for anything else are not even offered to the model.+- **It is yours, not the store's.** Each person connects for themselves, so an agent's actions are recorded against whoever approved it.++[Permissions and consent](/developer/mcp/permissions) covers this in full.++## The first conversation++The agent picks tools from what you ask; there is no command to learn.++> **You:** Which products are out of stock, and what did we sell in Germany last month?++It calls `describe_resource` to learn that products can be filtered by an `out_of_stock` scope, `search_resources` to list them, then `describe_reporting` and `query_report` for the German figures — and answers in one reply.++> **You:** Create a product called Expensive Bag with two variants, size S and M, 100 in stock each, priced 199 USD.++It calls `create_resource` once, with the variants, their prices and their stock levels nested in the same write.++> **You:** Cancel order R123456789 and tell the customer why.++It finds the order, then calls `orders_cancel`. Your client asks you to confirm before the call runs, because the tool declares that it changes data. Spree then runs the same cancellation the dashboard runs, and the order's timeline records who cancelled it.++## Check what it can see++Ask the agent directly — `describe_resource` with no arguments lists every resource the connection reaches, and the client's own tool list shows what it was offered. A connection approved for products alone sees roughly a dozen tools rather than all 58.++## Troubleshooting++<AccordionGroup>+ <Accordion title="The client says the server needs authorization and nothing happens">+ The endpoint advertises its authorization server at `/api/v3/oauth/protected-resource/mcp`. If your store sits behind a proxy that rewrites the host, the advertised URL has to be one the browser can reach — check that `Spree::Store#url` and the incoming `Host` header agree.+ </Accordion>++ <Accordion title="Connected, but the agent says it cannot do something">+ It was not granted that permission. **Settings → Connected apps** shows what each connection holds; revoke and reconnect to approve more. Tools outside the grant are not offered at all, so the agent will say it has no way to do it rather than failing mid-call.+ </Accordion>++ <Accordion title="A tool exists but refuses with a permission error">+ Tool visibility is per permission, but the data behind it is checked per record and per resource. A connection granted `read_reports` can run a report, and will still be refused a dimension that exposes customers unless it also holds `read_customers`.+ </Accordion>++ <Accordion title="Nothing is listed under Connected apps">+ Connections are per person. You are looking at your own; another staff member's connection appears under theirs.+ </Accordion>+</AccordionGroup>++## Next steps++<CardGroup cols={2}>+ <Card title="Tool reference" icon="wrench" href="/developer/mcp/tools">+ All 58 tools and the permission each needs.+ </Card>+ <Card title="Permissions and consent" icon="shield-check" href="/developer/mcp/permissions">+ How a grant is bounded, and what is out of reach whatever you approve.+ </Card>+ <Card title="Custom tools" icon="puzzle-piece" href="/developer/mcp/custom-tools">+ Add your own, or expose a workflow your extension ships.+ </Card>+ <Card title="Admin API" icon="code" href="/api-reference/admin">+ What every tool is dispatching to underneath.+ </Card>+</CardGroup>diff --git a/docs/developer/mcp/tools.mdx b/docs/developer/mcp/tools.mdxnew file mode 100644index 0000000000..25b33ca258--- /dev/null+++ b/docs/developer/mcp/tools.mdx@@ -0,0 +1,163 @@+---+title: "Tool Reference"+sidebarTitle: Tools+description: "Every tool the MCP server offers, what it is for and which permission it needs."+---++58 tools ship with the server. An agent is only ever shown the ones its grant permits, so a connection approved for products alone sees roughly a dozen.++The catalog is deliberately not a mirror of the API's 500-odd operations — a tool list that size makes a model worse at choosing, not better. Tools cover the operations a merchant asks for by name; everything else is reached through the three generic ones under [store setup](#store-setup).++<Note>+ The **Permission** column is what a grant must hold for the tool to be offered. A dash means the tool carries no permission of its own and is gated per resource instead: `search_resources` is offered to everyone, but only lists resources the grant can read.++ The last column says whether the tool reads or writes. A write asks your client to confirm before it runs.+</Note>++### Finding and reading++| Tool | Permission | |+| --- | --- | --- |+| `describe_resource` | — | read |+| `search_resources` | — | read |+| `get_resource` | — | read |++### Reporting++| Tool | Permission | |+| --- | --- | --- |+| `describe_reporting` | `read_reports` | read |+| `query_report` | `read_reports` | read |++### Catalog++| Tool | Permission | |+| --- | --- | --- |+| `products_activate` | `write_products` | write |+| `products_draft` | `write_products` | write |+| `products_archive` | `write_products` | write |+| `products_approve` | `write_products` | write |+| `products_reject` | `write_products` | write |+| `variants_create` | `write_products` | write |+| `variants_update` | `write_products` | write |+| `catalogs_activate` | `write_products` | write |+| `catalogs_deactivate` | `write_products` | write |+| `price_lists_activate` | `write_products` | write |+| `price_lists_deactivate` | `write_products` | write |+| `curate_products` | — | write |++### Orders and payments++| Tool | Permission | |+| --- | --- | --- |+| `orders_cancel` | `write_orders` | write |+| `orders_complete` | `write_orders` | write |+| `payments_capture` | `write_payments` | write |+| `payments_void` | `write_payments` | write |+| `refunds_create` | `write_refunds` | write |++### Fulfilment++| Tool | Permission | |+| --- | --- | --- |+| `fulfillments_create` | `write_fulfillments` | write |+| `fulfillments_mark_delivered` | `write_fulfillments` | write |+| `deliveries_update_tracking` | `write_orders` | write |+| `shipping_labels_purchase` | `write_orders` | write |+| `shipping_labels_refund` | `write_orders` | write |++### Stock and purchasing++| Tool | Permission | |+| --- | --- | --- |+| `set_stock` | `write_stock` | write |+| `stock_transfers_mark_draft` | `write_stock` | write |+| `stock_transfers_mark_ready` | `write_stock` | write |+| `stock_transfers_mark_in_transit` | `write_stock` | write |+| `stock_transfers_receive` | `write_stock` | write |+| `stock_transfers_cancel` | `write_stock` | write |+| `stock_transfers_close` | `write_stock` | write |+| `purchase_orders_mark_draft` | `write_purchasing` | write |+| `purchase_orders_mark_ordered` | `write_purchasing` | write |+| `purchase_orders_receive` | `write_purchasing` | write |+| `purchase_orders_cancel` | `write_purchasing` | write |+| `purchase_orders_close` | `write_purchasing` | write |++### Sellers++| Tool | Permission | |+| --- | --- | --- |+| `sellers_invite` | `write_sellers` | write |+| `sellers_approve` | `write_sellers` | write |+| `sellers_reject` | `write_sellers` | write |+| `sellers_suspend` | `write_sellers` | write |+| `sellers_reopen_onboarding` | `write_sellers` | write |+| `seller_requirement_submissions_accept` | `write_sellers` | write |+| `seller_requirement_submissions_reject` | `write_sellers` | write |+| `seller_requirement_submissions_waive` | `write_sellers` | write |++### Files++| Tool | Permission | |+| --- | --- | --- |+| `upload_file` | `write_products` | write |+| `media_create` | `write_media` | write |+| `create_import` | — | write |+| `propose_import_mapping` | — | write |+| `describe_import_mapping` | — | read |+| `get_import_status` | — | read |+| `create_export` | — | write |++### Store setup++| Tool | Permission | |+| --- | --- | --- |+| `create_resource` | — | write |+| `update_resource` | — | write |+| `delete_resource` | — | write |+| `tax_exemption_certificates_verify` | `write_customers` | write |+++## Resources++Beyond tools, the server offers MCP **resources** — files a client can fetch rather than operations it can run.++| Resource | What it is |+| --- | --- |+| `spree+export://<id>` | A finished export, as CSV. Reading one costs the same permission as reading the records in it. |++A product's media, an order's purchase order and an import's own file are things an agent *puts* there rather than reads back, so they are uploads rather than resources.++## What no tool will do++Some things are out of reach whatever a grant holds.++- **Credentials.** API keys, integrations, webhook endpoints and gift card codes are never returned by any tool. A gift card code is the money itself, and an integration's settings are where provider credentials live.+- **Minting another credential.** A grant cannot create API keys, roles, staff accounts or another OAuth client — so an agent can never widen its own reach.+- **Erasing a customer.** GDPR erasure is irreversible and is not something to put behind a single confirmation prompt. Do it in the dashboard.+- **Order editing.** Adding line items, discounts and fees to an existing order runs through paths that are not yet workflows. Cancelling, refunding and fulfilling all work today.++25 further workflows are excluded for reasons a contract spec enforces, so one cannot be exposed by accident.++## Writing records++Three tools cover every resource the Admin API can write, rather than one tool per resource:++- `create_resource`, `update_resource`, `delete_resource`++They dispatch to the real endpoint, so a resource whose controller runs a workflow gets that workflow. Two things worth knowing:++**Nested records travel with their parent.** A product's variants carry their own options, prices and stock levels in the same write, so creating a product with two sized variants is one call rather than four. `describe_resource` reports what fits inside each list.++**A list replaces rather than appends.** Sending one variant leaves a product with one variant. Send every row you want to keep.++## See also++<CardGroup cols={2}>+ <Card title="Permissions and consent" icon="shield-check" href="/developer/mcp/permissions">+ What a merchant approves and how a grant is bounded.+ </Card>+ <Card title="Custom tools" icon="puzzle-piece" href="/developer/mcp/custom-tools">+ Add your own, or expose a workflow your extension ships.+ </Card>+</CardGroup>diff --git a/docs/docs.json b/docs/docs.jsonindex cd18145087..07501e9360 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -699,6 +699,10 @@{"source": "/user/orders/creating-orders","destination": "/user/orders/draft-orders"+ },+ {+ "source": "/developer/agentic/admin-mcp",+ "destination": "/developer/mcp/overview"}],"contextual": {@@ -807,12 +811,22 @@"developer/agentic/overview","developer/agentic/agent-skills","developer/agentic/mcp",- "developer/agentic/admin-mcp","developer/agentic/llm-docs","developer/cli/admin-api"],"icon": "sparkles"},+ {+ "group": "MCP Server",+ "pages": [+ "developer/mcp/overview",+ "developer/mcp/quick-start",+ "developer/mcp/tools",+ "developer/mcp/permissions",+ "developer/mcp/custom-tools"+ ],+ "icon": "plug"+ },{"group": "Tutorial","pages": [@@ -2649,7 +2663,6 @@"developer/agentic/overview","developer/agentic/agent-skills","developer/agentic/mcp",- "developer/agentic/admin-mcp","developer/agentic/llm-docs"]}diff --git a/docs/plans/6.0-mcp-oauth.md b/docs/plans/6.0-mcp-oauth.mdindex 510fa64418..3f08a55ebc 100644--- a/docs/plans/6.0-mcp-oauth.md+++ b/docs/plans/6.0-mcp-oauth.md@@ -151,7 +151,7 @@ Steps 1–3 are the substance; a merchant sees nothing until 4 and 5.- **Do not add a second permission model.** A grant's authority is the adminuser's own, resolved at call time through the same ability the dashboarduses. Scopes on a grant narrow that authority; they never extend it.-- **The tool catalog is untouched.** `Spree.agent_tools`, the resource map and+- **The tool catalog is untouched.** `Spree.admin_agent_tools`, the resource map andthe credential filter are shared by both authentication paths and must notlearn which one a request used.diff --git a/docs/plans/6.0-mcp-server.md b/docs/plans/6.0-mcp-server.mdindex f55e14e341..7bd075df40 100644--- a/docs/plans/6.0-mcp-server.md+++ b/docs/plans/6.0-mcp-server.md@@ -40,7 +40,7 @@ so a tool reaches data exactly the way any other client does.Stripe gem can register a tool without depending on either the MCP or theassistant gem. A registry of names, schemas and permission keys carries noLLM dependency, so the assistant plan's rule that core takes none still- holds. Names: `Spree::AgentTool` (base class), `Spree.agent_tools`+ holds. Names: `Spree::AgentTool` (base class), `Spree.admin_agent_tools`(registry), `Spree::AgentTools::*` (built-ins). Not `spree_ai` or`spree_agents`: nothing intelligent runs in the registry, and a name thatpromised otherwise would claim the adapters' job.@@ -67,7 +67,7 @@ so a tool reaches data exactly the way any other client does.and a hybrid of first-class families plus a generic tail (two conventionsthat drift).- **Exposure is an allowlist in core, keyed by dependency key (2026-09-16).**- `Spree.agent_tools.expose_workflows(order_cancel_workflow: 'write_orders', …)`+ `Spree.admin_agent_tools.expose_workflows(order_cancel_workflow: 'write_orders', …)`lives in `spree_core`; workflows themselves stay untouched. Keying by thedependency key means a host app that swaps `Spree.order_cancel_workflow`for its own class keeps the tool, with the schema read from the@@ -263,7 +263,7 @@ Extracted from the assistant branch with a rename, not a rewrite:```spree/core/lib/spree/agent_tool.rb # base class: tool_name, description, param, permission, mutating!-spree/core/lib/spree/agent_tools/registry.rb # Spree.agent_tools — registered by class name, resolved on use+spree/core/lib/spree/agent_tools/registry.rb # Spree.admin_agent_tools — registered by class name, resolved on usespree/core/lib/spree/agent_tools/context.rb # {store, principal, ability, permission_keys}spree/core/lib/spree/agent_tools/resource_map.rbspree/core/lib/spree/agent_tools/record_summary.rb@@ -271,7 +271,7 @@ spree/core/app/tools/spree/agent_tools/*.rb # built-in tools```A tool is `{name, description, JSON params schema, permission key, mutating-flag, executor}`. Extensions register with `Spree.agent_tools << MyGem::Tools::SyncSupplier`+flag, executor}`. Extensions register with `Spree.admin_agent_tools << MyGem::Tools::SyncSupplier`exactly as they register a delivery-rate provider.**Context carries a principal, not a user.** The assistant's context holds the@@ -331,7 +331,7 @@ payload is the wrong default; `get_resource` is the full record.**The allowlist.** One file in core:```ruby-Spree.agent_tools.expose_workflows(+Spree.admin_agent_tools.expose_workflows(order_cancel_workflow: 'write_orders',order_complete_workflow: 'write_orders',fulfillment_create_workflow: 'write_orders',@@ -577,7 +577,7 @@ rule for the MCP catalog: if a write is not a workflow, it is not a tool yet.### The assistant, later-`6.0-dashboard-assistant.md` rebases onto `Spree.agent_tools`: its+`6.0-dashboard-assistant.md` rebases onto `Spree.admin_agent_tools`: its`Spree::Assistant::Tool` and registry are deleted, its RubyLLM adapter readsthe core registry, its context becomes a user-principal `Spree::AgentTools::Context`,and its approval gate keys off the same `mutating` flag. Chat persistence,@@ -766,7 +766,7 @@ history of a core contract and leave two copies to reconcile.| From `spree/assistant/…` | Lines | To `spree/core/…` ||---|---|---|| `lib/spree/assistant/tool.rb` | | `lib/spree/agent_tool.rb` — `Spree::AgentTool` |-| `lib/spree/assistant/registry.rb` | | `lib/spree/agent_tools/registry.rb` — exposed as `Spree.agent_tools` |+| `lib/spree/assistant/registry.rb` | | `lib/spree/agent_tools/registry.rb` — exposed as `Spree.admin_agent_tools` || `lib/spree/assistant/context.rb` | | `lib/spree/agent_tools/context.rb` — gains the principal || `lib/spree/assistant/resource_map.rb` | | `lib/spree/agent_tools/resource_map.rb` — derived from controllers || `lib/spree/assistant/record_summary.rb` | | `lib/spree/agent_tools/record_summary.rb` |@@ -788,7 +788,7 @@ unaffected beyond the rebase.1. **Rename.** `Spree::Assistant::Tool` → `Spree::AgentTool`,`Spree::Assistant::Tools::X` → `Spree::AgentTools::X`,- `Spree::Assistant.tools` → `Spree.agent_tools`. Tool *names* on the wire+ `Spree::Assistant.tools` → `Spree.admin_agent_tools`. Tool *names* on the wire(`search_resources`, `update_product_status`, …) do not change: theassistant's persisted tool-call rows reference them.2. **Principal on the context.** `Context.new(store:, user:)` keeps working@@ -821,7 +821,7 @@ unaffected beyond the rebase.MCP or LLM code in it.3. After it merges, rebase `feat/dash-assistant` onto `main`, delete themoved files from `spree/assistant`, point the RubyLLM adapter and- `RunTurn` at `Spree.agent_tools` and the core context, and run the+ `RunTurn` at `Spree.admin_agent_tools` and the core context, and run theassistant suite. The branch shrinks by the lines core gained.4. `spree_mcp` (step 4 of the Migration Path) starts from `main` once step1 is in; it never branches from the assistant.diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/reporting_authorization.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/reporting_authorization.rbindex 8ba590c3ad..2a4fb4eca9 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/reporting_authorization.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/reporting_authorization.rb@@ -3,22 +3,31 @@ module Spreemodule V3module Admin# Per-member authorization for the reporting vocabulary. Metrics,- # dimensions and counters all declare a `subject` (checked for JWT- # staff through CanCanCan) paired with a `key_scope` (checked for- # secret keys), so one predicate answers for every member and every+ # dimensions and counters all declare a `key_scope` paired with a+ # `subject`, so one predicate answers for every member and every# surface that lists them — the schema, a query, the home screen's# counters — filters by the same rule.+ #+ # Asked of the credential rather than of its owner. Branching on+ # `current_api_key` measured an OAuth grant against the approving+ # staff member's whole role, because a token authenticates as that+ # person and carries no key: a grant for `read_reports` alone could+ # group a report by customer and read names, emails and spend.+ # `holds_permission?` is the narrowed answer for all three+ # principals — a key's scopes, a grant's, or the role when someone is+ # acting directly at the dashboard.module ReportingAuthorizationextend ActiveSupport::Concernprivatedef member_allowed?(member)- if current_api_key.present?- member.key_scope.blank? || current_api_key.has_scope?(member.key_scope)- else- member.subject.nil? || can?(:read, member.subject.call)- end+ return false unless member.key_scope.blank? || holds_permission?(member.key_scope)++ # The permission says whether this kind of data is in scope at+ # all; a host app's record-level rule can still narrow which of+ # it this person sees.+ member.subject.nil? || can?(:read, member.subject.call)endendenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rbindex a10f55b15e..e4c9b821dc 100644--- a/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb@@ -87,27 +87,33 @@ module Spreeparams.to_unsafe_h.slice(*QUERY_KEYS)end- # Both credential types are authorized per referenced member:- # JWT admins via CanCanCan (`required_subjects`), secret keys via- # their scopes (`required_key_scopes` on top of the `read_reports`- # endpoint gate) — a key without `read_products` cannot query the- # product dimension any more than a limited staff role can.+ # Every referenced member is authorized against what this+ # credential holds, on top of the `read_reports` endpoint gate: a+ # caller without `read_products` cannot query the product dimension+ # whatever its principal type.+ #+ # Asked through `holds_permission?` rather than of the ability,+ # because an OAuth grant authenticates as the staff member who+ # approved it and carries no API key. Measured against their role,+ # a grant for `read_reports` alone could group by customer and read+ # names, emails and spend — data the merchant never consented to.def authorize_reporting_members!(reporting_query)- if current_api_key.present?- missing = reporting_query.required_key_scopes.reject { |scope| current_api_key.has_scope?(scope) }- return if missing.empty?+ missing = reporting_query.required_key_scopes.reject { |scope| holds_permission?(scope) }- render_error(+ if missing.any?+ return render_error(code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],- message: "API key lacks scope: #{missing.join(', ')}",+ message: "Missing permission: #{missing.join(', ')}",status: :forbidden,details: { required_scopes: missing })- else- authorize!(:read, :reports)- forbidden = reporting_query.unreadable_subjects(current_ability).first- raise CanCan::AccessDenied.new(nil, :read, forbidden) if forbiddenend++ # Then the record-level rules, which a host app uses to narrow+ # what a role sees within data it may read at all.+ authorize!(:read, :reports)+ forbidden = reporting_query.unreadable_subjects(current_ability).first+ raise CanCan::AccessDenied.new(nil, :read, forbidden) if forbiddenend# An unknown member carries what it was and what was valid instead.diff --git a/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rb b/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rbindex 25c74aaf6d..f43a21af81 100644--- a/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rb@@ -37,7 +37,7 @@ module Spree# than it accepts turns every connection into "The requested# scope is invalid".scopes_supported: Spree::Api::Oauth.staff_scope_keys,- resource_documentation: 'https://spreecommerce.org/docs/developer/agentic/admin-mcp'+ resource_documentation: 'https://spreecommerce.org/docs/developer/mcp/overview')render json: Spree.api.admin_oauth_protected_resource_serializer.new(document).to_hdiff --git a/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb b/spree/api/spec/lib/spree/agent_tools/authorization_spec.rbindex 7adc60d31e..c713717e05 100644--- a/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb+++ b/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb@@ -91,7 +91,7 @@ RSpec.describe 'assistant authorization' do# workflow tool that replaced it.describe 'changes, through the workflow tool' dolet(:tool) do- Spree.agent_tools.available_for(context).find { |candidate| candidate.tool_name == 'products_draft' }+ Spree.admin_agent_tools.available_for(context).find { |candidate| candidate.tool_name == 'products_draft' }endit 'refuses a record the ability excludes' do@@ -130,7 +130,7 @@ RSpec.describe 'assistant authorization' doendit 'creates without demanding permission over the store or the actor' do- tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'create_resource' }+ tool = Spree.admin_agent_tools.available_for(context).find { |t| t.tool_name == 'create_resource' }result = tool.call(resource: 'products', attributes: { 'name' => "Agent Made #{SecureRandom.hex(3)}" })expect(result[:error]).to be_nil@@ -138,7 +138,7 @@ RSpec.describe 'assistant authorization' doendit 'names the created record in the summary, not the store' do- tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'create_resource' }+ tool = Spree.admin_agent_tools.available_for(context).find { |t| t.tool_name == 'create_resource' }result = tool.call(resource: 'products', attributes: { 'name' => 'Summary Subject' })expect(result[:summary]).to include('Summary Subject')@@ -157,7 +157,7 @@ RSpec.describe 'assistant authorization' doendit 'refuses the create workflow' do- create_tool = Spree.agent_tools.available_for(context).+ create_tool = Spree.admin_agent_tools.available_for(context).find { |candidate| candidate.tool_name == 'create_resource' }result = create_tool.call(resource: 'products', attributes: { 'name' => 'Should Not Exist' })@@ -177,7 +177,7 @@ RSpec.describe 'assistant authorization' doendit 'refuses the destroy workflow' do- destroy = Spree.agent_tools.available_for(context).+ destroy = Spree.admin_agent_tools.available_for(context).find { |candidate| candidate.tool_name == 'delete_resource' }result = destroy.call(resource: 'products', id: visible.prefixed_id)diff --git a/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rb b/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rbindex aba28652dc..d3838d816b 100644--- a/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rb+++ b/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rb@@ -1,7 +1,7 @@require 'spec_helper'# The registry is a public extension point, and-# docs/developer/agentic/admin-mcp.mdx tells an author to write exactly this+# docs/developer/mcp/custom-tools.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@@ -25,16 +25,16 @@ RSpec.describe 'the extension path the docs describe' do{ summary: "#{sku}: #{stock} available", sku: sku, available: stock }endend)- Spree.agent_tools << 'MyShop::AgentTools::SupplierStock'+ Spree.admin_agent_tools << 'MyShop::AgentTools::SupplierStock'endit 'is offered to a key holding the permission' do- names = Spree.agent_tools.available_for(context).map(&:tool_name)+ names = Spree.admin_agent_tools.available_for(context).map(&:tool_name)expect(names).to include('supplier_stock')endit 'answers and refuses as documented' do- tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'supplier_stock' }+ tool = Spree.admin_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@@ -43,6 +43,6 @@ RSpec.describe 'the extension path the docs describe' doother = create(:api_key, :secret, store: store, scopes: ['read_products'])ctx = Spree::AgentTools::Context.new(store: store, api_key: other, request_headers: agent_headers_for_key(other))- expect(Spree.agent_tools.available_for(ctx).map(&:tool_name)).not_to include('supplier_stock')+ expect(Spree.admin_agent_tools.available_for(ctx).map(&:tool_name)).not_to include('supplier_stock')endenddiff --git a/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rbindex 0d7870bfec..041f233ac8 100644--- a/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rb+++ b/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rb@@ -67,6 +67,31 @@ RSpec.describe 'Admin API OAuth access', type: :request doexpect(product.reload.name).to eq('Espresso Machine')end+ # Reporting gates each dimension on the scope for the data it exposes,+ # so a grant for reports alone must not reach customer names, emails and+ # spend by grouping on them.+ it 'cannot report on a dimension outside its scopes' do+ post '/api/v3/admin/reporting/query',+ params: { metrics: ['net_sales'], dimensions: ['customer'] }.to_json,+ headers: { 'Authorization' => "Bearer #{token_for('read_reports', resource: '/api/v3/admin')}",+ 'CONTENT_TYPE' => 'application/json' }++ expect(response).to have_http_status(:forbidden)+ expect(JSON.parse(response.body).dig('error', 'message')).to include('read_customers')+ end++ # And the vocabulary it is offered matches, so it is not told to ask for+ # something it would be refused.+ it 'is not offered a dimension it may not use' do+ get '/api/v3/admin/reporting/schema',+ headers: { 'Authorization' => "Bearer #{token_for('read_reports', resource: '/api/v3/admin')}" }++ names = JSON.parse(response.body)['dimensions'].map { |dimension| dimension['name'] }++ expect(names).to include('completed_at')+ expect(names).not_to include('customer')+ end+# The widest version of the same fault: the consent endpoint mints# grants, so an agent that could reach it with its owner's whole role# could approve itself anything that role can do — and a grant is adiff --git a/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb b/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rbindex 09082eef06..e0f4e2e065 100644--- a/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb@@ -9,7 +9,7 @@ RSpec.describe 'agent product curation' dolet(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }def tool(ctx = context)- Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'curate_products' }+ Spree.admin_agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'curate_products' }enddescribe 'the derived set of parents' dodiff --git a/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb b/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rbindex 2b980deae8..9b30ad1d89 100644--- a/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb@@ -11,7 +11,7 @@ RSpec.describe 'agent reporting tools' dolet(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }def tool(name)- Spree.agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }+ Spree.admin_agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }enddescribe 'describe_reporting' do@@ -106,7 +106,7 @@ RSpec.describe 'agent reporting tools' dolet(:scopes) { ['read_products'] }it 'is not offered the reporting tools' do- names = Spree.agent_tools.available_for(context).map(&:tool_name)+ names = Spree.admin_agent_tools.available_for(context).map(&:tool_name)expect(names).not_to include('query_report', 'describe_reporting')end@@ -124,7 +124,7 @@ RSpec.describe 'agent reporting tools' doendit 'refuses to group by it' do- tool = Spree.agent_tools.available_for(narrow).find { |t| t.tool_name == 'query_report' }+ tool = Spree.admin_agent_tools.available_for(narrow).find { |t| t.tool_name == 'query_report' }result = tool.call(metrics: ['gross_sales'], dimensions: ['product'])@@ -133,7 +133,7 @@ RSpec.describe 'agent reporting tools' doendit 'still allows one the grant covers' do- tool = Spree.agent_tools.available_for(narrow).find { |t| t.tool_name == 'query_report' }+ tool = Spree.admin_agent_tools.available_for(narrow).find { |t| t.tool_name == 'query_report' }result = tool.call(metrics: ['gross_sales'], dimensions: ['completed_at'])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.rbindex f281f903cf..fbeb038eaa 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@@ -9,7 +9,7 @@ RSpec.describe 'agent generic record writes' dolet(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }def tool(name)- Spree.agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }+ Spree.admin_agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }enddescribe 'update_resource' do@@ -114,7 +114,7 @@ RSpec.describe 'agent generic record writes' do# attributes a resource accepts, so it has to answer that question.describe 'describe_resource and the write tools agree' doit 'lists the attributes a generic write accepts' do- described = Spree.agent_tools.available_for(context).+ described = Spree.admin_agent_tools.available_for(context).find { |candidate| candidate.tool_name == 'describe_resource' }.call(resource: 'markets')[:resources].first@@ -122,7 +122,7 @@ RSpec.describe 'agent generic record writes' doendit 'names the create and update tools separately' do- described = Spree.agent_tools.available_for(context).+ described = Spree.admin_agent_tools.available_for(context).find { |candidate| candidate.tool_name == 'describe_resource' }.call(resource: 'products')[:resources].first@@ -163,7 +163,7 @@ RSpec.describe 'agent generic record writes' dolet(:api_key) { create(:api_key, :secret, store: store, scopes: ['read_all']) }it 'is not offered the write tools at all' do- names = Spree.agent_tools.available_for(context).map(&:tool_name)+ names = Spree.admin_agent_tools.available_for(context).map(&:tool_name)expect(names).not_to include('create_resource', 'update_resource', 'delete_resource')enddiff --git a/spree/api/spec/tools/spree/agent_tools/set_stock_spec.rb b/spree/api/spec/tools/spree/agent_tools/set_stock_spec.rbindex 278ec01d83..b70060f004 100644--- a/spree/api/spec/tools/spree/agent_tools/set_stock_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/set_stock_spec.rb@@ -19,7 +19,7 @@ RSpec.describe 'agent stock setting' doenddef tool(ctx = context)- Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'set_stock' }+ Spree.admin_agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'set_stock' }enddef row(**attributes)diff --git a/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb b/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rbindex 109aac15fd..45e07a8c2a 100644--- a/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb@@ -12,7 +12,7 @@ RSpec.describe 'agent tools that consume an upload' doenddef tool(name, ctx = context)- Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == name }+ Spree.admin_agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == name }end# Text as text. A model emits every byte of its arguments, so base64 isdiff --git a/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rb b/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rbindex f6f23d9f04..8e649be46a 100644--- a/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rb@@ -8,7 +8,7 @@ RSpec.describe 'agent file upload' dolet(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }def tool(ctx = context)- Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'upload_file' }+ Spree.admin_agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'upload_file' }end# Text as text, which is the default now: a model has to emit every bytediff --git a/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb b/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rbindex 2004dd1743..5ba77879a5 100644--- a/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb@@ -9,7 +9,7 @@ RSpec.describe 'agent workflow tool arguments' dolet(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }def tool(name)- Spree.agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }+ Spree.admin_agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }enddescribe 'records named inside a list of rows' do@@ -131,7 +131,7 @@ RSpec.describe 'agent workflow tool arguments' doit 'records an admin user, which the association does accept' doadmin = create(:admin_user)admin_context = Spree::AgentTools::Context.new(store: store, user: admin, request_headers: agent_headers_for(admin))- admin_tool = Spree.agent_tools.available_for(admin_context).+ admin_tool = Spree.admin_agent_tools.available_for(admin_context).find { |candidate| candidate.tool_name == 'create_resource' }result = admin_tool.call(diff --git a/spree/core/lib/spree/agent_tool.rb b/spree/core/lib/spree/agent_tool.rbindex 5500423a08..993874fbcd 100644--- a/spree/core/lib/spree/agent_tool.rb+++ b/spree/core/lib/spree/agent_tool.rb@@ -1,5 +1,5 @@module Spree- # One entry in the agent-tool registry ({Spree.agent_tools}).+ # One entry in the agent-tool registry ({Spree.admin_agent_tools}).## A tool is a plain Spree object: a name, a description the model reads, a# JSON parameter schema, the permission key that gates it, whether it@@ -31,6 +31,7 @@ class AgentToolclass_attribute :declared_description, instance_accessor: falseclass_attribute :declared_permission, instance_accessor: falseclass_attribute :declared_mutating, instance_accessor: false, default: false+ class_attribute :declared_audience, instance_accessor: false, default: :adminclass_attribute :declared_params, instance_accessor: false, default: {}.freezeclass << self@@ -55,6 +56,22 @@ class AgentTooldeclared_permissionend+ # Which surface this tool belongs to: `:admin` for the back office,+ # `:store` for the storefront.+ #+ # Declared on the tool rather than inferred from the registry it was+ # pushed into, so filing one in the wrong place is refused at+ # registration. It matters most for the tools that carry no permission+ # of their own — they are gated per resource, and a blank permission+ # reads as "anyone may see this".+ #+ # @param value [Symbol, nil]+ # @return [Symbol]+ def audience(value = nil)+ self.declared_audience = value.to_sym if value+ declared_audience+ end+# Declares that this tool changes store data, so the turn halts for# human approval instead of executing.#diff --git a/spree/core/lib/spree/agent_tools/registry.rb b/spree/core/lib/spree/agent_tools/registry.rbindex d9bcaa4ad4..7b02ccadbb 100644--- a/spree/core/lib/spree/agent_tools/registry.rb+++ b/spree/core/lib/spree/agent_tools/registry.rb@@ -1,13 +1,22 @@module Spreemodule AgentTools- # The agent-tool registry, reached as {Spree.agent_tools}. Extensions append- # their own tool classes the same way they register tax or delivery-rate+ # The agent-tool registry. One per surface, the way the authentication+ # strategies are split — {Spree.admin_agent_tools} for the back office,+ # {Spree.store_agent_tools} for the storefront. Extensions append their+ # own tool classes the same way they register tax or delivery-rate# providers:#- # Spree.agent_tools << MyApp::AgentTools::SyncSupplier+ # Spree.admin_agent_tools << MyApp::AgentTools::SyncSupplier#- # Registration is by class, so one registry serves every adapter: the MCP- # server and the dashboard assistant both read it.+ # Registration is by class, so one registry serves every adapter on its+ # surface: the MCP server and the dashboard assistant both read the admin+ # one.+ #+ # A tool also declares the surface it belongs to, so filing one in the+ # wrong registry is refused rather than discovered when a storefront+ # visitor is offered the back office. Ten admin tools carry no permission+ # of their own — they are gated per resource instead — so the registry+ # cannot be the only thing keeping them apart.## Writes are not registered as classes. A back-office write already is a# workflow, so the registry exposes workflows by their `Spree::Dependencies`@@ -16,9 +25,13 @@ module Spreeclass Registryinclude Enumerable- def initialize(tool_names = [])+ # @return [Symbol] the surface this registry serves+ attr_reader :audience++ def initialize(tool_names = [], audience: :admin)@tool_names = tool_names.map(&:to_s)@exposed_workflows = {}+ @audience = audience.to_symend# Registered by name, resolved on use.@@ -33,6 +46,12 @@ module Spree# @return [self]def <<(tool_class)name = tool_class.to_s+ declared = tool_class.try(:audience)+ if declared && declared != audience+ raise ArgumentError,+ "#{name} belongs to the #{declared} surface and cannot be registered on the #{audience} one"+ end+@tool_names << name unless @tool_names.include?(name)selfend@@ -45,7 +64,7 @@ module Spree# Exposes workflows as write tools, keyed by `Spree::Dependencies` key so# the tool follows whatever class the host app has registered:#- # Spree.agent_tools.expose_workflows(+ # Spree.admin_agent_tools.expose_workflows(# order_cancel_workflow: 'write_orders',# product_activate_workflow: 'write_products'# )@@ -83,7 +102,10 @@ module Spree# @param context [Spree::AgentTools::Context]# @return [Array<Spree::AgentTool>]def available_for(context)- to_a.map { |tool_class| tool_class.new(context) }.select(&:permitted?)+ to_a.+ select { |tool_class| tool_class.try(:audience).nil? || tool_class.audience == audience }.+ map { |tool_class| tool_class.new(context) }.+ select(&:permitted?)endprivatediff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 12f3036dbb..cfc3a0d791 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -522,7 +522,8 @@ module Spree# either adapter. See docs/plans/6.0-mcp-server.md.## @return [Spree::AgentTools::Registry]- singleton_class.delegate :agent_tools, :agent_tools=, to: :spree_config+ singleton_class.delegate :admin_agent_tools, :admin_agent_tools=, to: :spree_config+ singleton_class.delegate :store_agent_tools, :store_agent_tools=, to: :spree_config# The permission catalog — the grant vocabulary shared by staff roles and# secret API key scopes. Roles themselves are data (Spree::Role#permissions);diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex f468378363..98af26773e 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -43,7 +43,8 @@ module Spree:actor_classes,:custom_fields,:reporting,- :agent_tools,+ :admin_agent_tools,+ :store_agent_tools,:integrations,:number_generators,:subscribers,@@ -162,9 +163,14 @@ module Spree# Seed the agent-tool registry before app initializers so applications# and extensions can register their own tools and expose their own# workflows in config/initializers (see docs/plans/6.0-mcp-server.md).+ # One registry per surface, the way the authentication strategies are+ # split: a storefront agent and a back-office agent share the tool+ # machinery but never the catalog, and a staff tool reaching a customer+ # would be offering the back office to the public.initializer 'spree.register.agent_tools', before: :load_config_initializers do |app|- app.config.spree.agent_tools = Spree::AgentTools::Registry.new- Spree::AgentTools::DefaultCatalog.install(app.config.spree.agent_tools)+ app.config.spree.admin_agent_tools = Spree::AgentTools::Registry.new(audience: :admin)+ app.config.spree.store_agent_tools = Spree::AgentTools::Registry.new(audience: :store)+ Spree::AgentTools::DefaultCatalog.install(app.config.spree.admin_agent_tools)enddiff --git a/spree/core/spec/lib/spree/agent_tools/context_spec.rb b/spree/core/spec/lib/spree/agent_tools/context_spec.rbindex babd60cd5e..7626264a29 100644--- a/spree/core/spec/lib/spree/agent_tools/context_spec.rb+++ b/spree/core/spec/lib/spree/agent_tools/context_spec.rb@@ -46,8 +46,8 @@ RSpec.describe Spree::AgentTools::Context doendit 'offers only the tools the grant covers' do- expect(Spree.agent_tools.available_for(context).size).- to be < Spree.agent_tools.available_for(unrestricted).size+ expect(Spree.admin_agent_tools.available_for(context).size).+ to be < Spree.admin_agent_tools.available_for(unrestricted).sizeendenddiff --git a/spree/mcp/README.md b/spree/mcp/README.mdindex 18584f9188..f129331943 100644--- a/spree/mcp/README.md+++ b/spree/mcp/README.md@@ -16,9 +16,9 @@ scopes decide which tools the model is offered, so an agent is never told abouta capability its credential does not carry.This gem is a protocol adapter and nothing more. The tools, their schemas and-the permissions gating them live in `spree_core` as `Spree.agent_tools`, which+the permissions gating them live in `spree_core` as `Spree.admin_agent_tools`, whichmeans an extension registers a tool without depending on this gem, and thedashboard assistant offers the same tools over a different transport.-See the [documentation](https://spreecommerce.org/docs/developer/agentic/admin-mcp)+See the [documentation](https://spreecommerce.org/docs/developer/mcp/overview)and `docs/plans/6.0-mcp-server.md`.diff --git a/spree/mcp/lib/spree/mcp/server.rb b/spree/mcp/lib/spree/mcp/server.rbindex 13794d8eb0..574c7fe632 100644--- a/spree/mcp/lib/spree/mcp/server.rb+++ b/spree/mcp/lib/spree/mcp/server.rb@@ -108,7 +108,7 @@ module Spree# @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) }+ Spree.admin_agent_tools.available_for(context).map { |tool| ToolAdapter.build(tool) }endendenddiff --git a/spree/mcp/lib/spree_mcp.rb b/spree/mcp/lib/spree_mcp.rbindex 6818a27394..f243dae308 100644--- a/spree/mcp/lib/spree_mcp.rb+++ b/spree/mcp/lib/spree_mcp.rb@@ -10,7 +10,7 @@ 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+ # A thin protocol adapter over {Spree.admin_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.