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.

57.8 KB
Raw Blame

Admin MCP Server

Status: In Review — Migration Path steps 1–5 built on feat/spree-mcp-server, PR spree/spree#14664. Step 6 (execution through the Admin API) is the direction the branch is moving to before merge, decided 2026-10-10: the in-process execution path the first five steps built is being replaced, the tool catalog is not. Target: Spree 6.0 Depends on: 6.0-action-actors.md (shipped 2026-09-16 — the API key is a valid actor, so a workflow run over MCP records who did it), 5.5-admin-api-cli.md (shipped — the CLI-first precondition this plan waited on), 5.5-admin-api-key-scopes.md (shipped — secret keys + scopes are the credential), 6.0-admin-rbac.md (the permission catalog gates every tool), 6.0-analytics-semantic-layer.md (the reporting registry feeds the reporting tools), 6.0-service-workflows.md (writes execute through workflows), 6.0-dashboard-assistant.md (moves onto the registry defined here) Author: Damian Legawiec (design driven with Claude) Last updated: 2026-10-10 Tracking: Linear V-3645 · GitHub spree/spree#14656

Summary

A Model Context Protocol server for the back office, so any MCP client — Claude Code, Claude Desktop and claude.ai connectors, Cursor, in-house agents — can merchandise the catalog, query the reporting engine and manage store setup (markets, channels, delivery, payments) in plain language, under the same tenancy and permission rules as the Admin API. The server is a thin protocol adapter over a Spree-owned agent-tool registry that lives in spree_core; the dashboard chat assistant (6.0-dashboard-assistant.md, unmerged) becomes the second adapter over that same registry once this ships. The order is deliberate: MCP first, assistant second. The registry is not a mirror of the Admin API: generic read and write tools mapped to the list, show, create, update and destroy operations, reporting tools mapped to the reporting endpoints, and one tool per non-CRUD member action (cancel, complete, capture, fulfil, approve, activate). Every schema comes from the operation's OpenAPI request shape, and every call is dispatched through the Admin API in-process, so a tool reaches data exactly the way any other client does.

Key Decisions (do not deviate without discussion)

  • MCP ships first, the assistant follows (2026-09-15). The CLI plan's ordering (CLI → MCP → assistant) is now the sequence: spree api has shipped, so the "no MCP before the CLI" constraint is satisfied. The assistant branch already holds a registry designed for exactly this reuse; this plan extracts that registry into core, ships the MCP adapter on it, and the assistant rebases onto it. The assistant plan's "No MCP in 6.0" decision is superseded by this plan (see decisions.md, 2026-09-15).

  • The registry lives in spree_core, no new gem (2026-09-15). It is a contract like Spree.integrations, Spree.tax_providers and Spree.reporting, and core is where Spree keeps contracts: an EasyPost or Stripe gem can register a tool without depending on either the MCP or the assistant gem. A registry of names, schemas and permission keys carries no LLM dependency, so the assistant plan's rule that core takes none still 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 that promised otherwise would claim the adapters' job.

  • Never one tool per endpoint; tools come from registries (2026-09-15). Narrowed 2026-11-03 by 6.0-agent-tools-from-openapi.md: every non-CRUD write operation is now a tool of its own; CRUD stays generic, and a custom read is a tool only when its spec opts it in. The Admin API has ninety-five controllers; wrapping them would produce two hundred plus tools, and the CLI plan already priced that (a ninety-three-tool server costs roughly fifty-five thousand tokens of context; some clients cap at forty). The catalog is four tiers — generic reads, reporting, workflow tools, generic record writes — and its parameters come from registries Spree already maintains, never from hand-written lists (see Design Details).

  • Operations are the write tools (2026-10-10; replaces "Workflows are the write tools", 2026-09-16). A tool names an Admin API operation, and the controller behind it runs whatever workflow it declares. The earlier decision reached for the workflow directly because its perform signature and YARD block were the only machine-readable contract available; the operation's OpenAPI request schema is a better one, and it is the contract clients already use. What the catalog keys on therefore changes too — see "the catalog is keyed by operation" below.

    The earlier reasoning still holds for why writes are safe: the base controller calls the declared create_workflow / update_workflow rather than saving records, so dispatching to it runs the same gate. Rejected: a single run_workflow tool (every write becomes two or three calls and the client can only confirm "run_workflow", not the action) and a hybrid of first-class families plus a generic tail (two conventions that drift).

  • Exposure is an allowlist in core, keyed by dependency key (2026-09-16). Superseded 2026-11-03 by 6.0-agent-tools-from-openapi.md: exposure is opt-out over the OpenAPI document, and expose_workflows is a deprecated no-op. Spree.admin_agent_tools.expose_workflows(order_cancel_workflow: 'write_orders', …) lives in spree_core; workflows themselves stay untouched. Keying by the dependency key means a host app that swaps Spree.order_cancel_workflow for its own class keeps the tool, with the schema read from the replacement's signature. Internal workflows (recalculation, cart merge, webhook handling, payout sweeps) are simply not listed. A contract spec keeps the list honest against the controllers, which remain the reference wiring for how a request becomes workflow keywords. Rejected: a declaration on each workflow class (scatters the catalog across 57 files) and a generated manifest from controller source (a second admin.yaml to regenerate).

  • Workflows only; Tier 1 services are promoted, not adapted (2026-09-16; withdrawn 2026-10-10). This gated exposure on a service becoming a workflow, because the adapter needed a perform signature to derive a schema from. Dispatch needs no signature: an endpoint backed by a service is as reachable as one backed by a workflow. So order editing, fees, discounts and stock become exposable as soon as their endpoints exist. Services are still promoted to workflows for their own sake — hooks, one gate per write — but that work no longer blocks agents. The original text read: seventeen services the admin controllers still call are not exposed; order editing reaches agents as those paths become workflows, never through a second adapter for call signatures.

  • Secret API keys with scopes are the credential; OAuth is a later lane (2026-09-15). The server authenticates with the same sk_ key and X-Spree-API-Key header as the Admin API and offers only the tools the key's scopes permit. Consumer connectors that require OAuth 2.1 (claude.ai hosted connectors, ChatGPT) wait on an authorization-server capability Spree does not have; 6.0-platform-auth phase 7 is OIDC login, which is not it. The transport, tool catalog and scope filtering are unchanged when OAuth arrives, so nothing here is throwaway.

  • The key travels as a header, in either of two forms (2026-09-16). X-Spree-API-Key: sk_…, the Admin API's header, or Authorization: Bearer sk_…, because several MCP clients offer only a bearer-token field and no custom header. The sk_ prefix keeps it unambiguous against the JWTs the Admin API accepts in the same header; the MCP controller refuses a JWT outright. No login, redirect or refresh: the key is the whole credential, and revocation in the dashboard is how it ends.

  • Writes are scope-gated on the server and confirmed by the client (2026-09-15). MCP has no approval card. A tool marked mutating is offered only to a key holding the matching write_* scope, and every mutating tool returns a one-line human summary of what it did so the client's own confirmation prompt (Claude Code and Claude Desktop ask before running a tool) has something to show. The assistant's server-side approval gate remains an assistant concern, built on the same mutating flag.

  • Tools execute through the Admin API, not beside it (2026-10-10). Superseding the execution half of the decisions below. The first five steps built the tools as a second way into the same data: their own store scoping, their own permission checks, their own Ransack call, their own writable attribute lists, their own error shape. Three faults found by probing the branch show the cost, and all three are the same fault:

    • A prefixed id filters nothing. search_resources calls .ransack directly, skipping the ResourceController step that decodes prefixed ids. Filtering variants by product_id_eq: "prod_3uWpPTcf5W" — the only form the tools ever return — answers total=0, where the raw id answers 3. No error: a model reports the empty result as fact.
    • Extension attributes are invisible. The writable list is derived from each controller's resource_permitted_attributes but not from the model's additional_permitted_attributes, so an extension adding brand_id can be written through the API and not through an agent.
    • A workflow trusted ids its one caller had already scoped. The stock upsert wrote to whichever shelf an id named, including another store's, because the check lived in the controller. Fixed by moving the scoping into the workflow — which is the same lesson at a smaller scale.

    Every guard added to the Admin API should protect agents by construction, not after someone remembers to copy it. So a tool call runs the real request path: routing, authentication, the controller, the serializer, the error format.

  • In-process dispatch, never HTTP to itself (2026-10-10). The Ruby adapter builds a Rack env and calls Rails.application.call, forwarding the caller's own credential and Host header — no internal "trusted" header that skips authentication, which would rebuild the second boundary this decision exists to remove. A socket back to the same app holds one Puma thread waiting on another, so a handful of concurrent tool calls on a small pool deadlocks the app; dispatch has the same behaviour without that, and without TLS, DNS or timeouts.

    Spree::Current does not reset across a nested dispatch, because the executor is re-entrant. Probed on this branch: an inner call left the outer request's store intact but overwrote its currency (GBP → USD). The adapter snapshots and restores Spree::Current around every dispatch, and a spec proves a tool call cannot see or corrupt the MCP request's own state. Tool calls do not run inside a transaction opened by the MCP controller — each commits or rolls back on its own, like any API request.

  • The catalog is the asset; the executor is replaceable (2026-10-10). Each entry names its operation, its permission, its description and a parameter projection. Parameter schemas come from OpenAPI — request bodies, x-spree-filters, the typed preference unions — rather than from Ruby signatures, which is why order creation needed a hand-written tool at all (its workflow takes an opaque params hash). At 7 the same catalog runs under TypeScript with @spree/admin-sdk, differing only in which fetch it is given: global fetch for a remote store, the app's own fetch in-process. The Ruby adapter is a shim with a known end date.

  • The catalog is keyed by operation, not by dependency key (2026-10-10). The step 1–5 allowlist keyed on Spree::Dependencies, a mechanism with an end date (it is being replaced by workflow hooks), and its contract spec scanned controller source for Spree.<key> calls. Keying on the OpenAPI operation instead lets the contract spec walk admin.yaml: every admin operation is either in the catalog or on the exclusion list with a reason. That is sturdier than reading Ruby source, and it is the same list a TypeScript executor reads at 7.

  • One agent turn is one unit of work for rate limiting (2026-10-10). The limiter must not see both the MCP request and each call it dispatches, or a single turn counts twice and an agent is throttled at half the rate its credential allows. Count the dispatched operations — those are the real work — and exempt the MCP envelope.

  • Compact results are the adapter's job until the API has sparse fields (2026-10-10). Index operations return the full admin payload, which is more than a model needs and more than its context should hold. If the Admin API gains sparse fieldsets the adapter passes the requested fields through; until then it trims the response itself. Written down because it decides whether "compact by design" is free or is work.

  • A missing endpoint is added to the Admin API first (2026-10-10). The rule the dashboard already follows. The stock upsert and product curation this branch reached directly become endpoints, and the tools point at them.

  • Tools execute through workflows, never by writing models (2026-09-15). A workflow tool calls the registered workflow; a generic record write exists only for a resource whose controller declares no workflow and takes the exact path the controller takes for it. Validations, hooks, events and webhooks fire exactly as from the dashboard or the API. The MCP server never opens a connection to itself; it dispatches to its own endpoints in-process.

  • Official mcp Ruby gem, served by a Spree controller, not by the gem's Rack transport (2026-09-15; transport detail corrected 2026-09-16). The gem is maintained by the protocol's working group and has supported the stateless 2026-07-28 revision since 1.2.0 (current 1.5.1). Its Rack transport takes one pre-built server for every request, which cannot carry a per-request principal, so the endpoint is an ordinary admin API controller: it authenticates the secret key with the existing concern, builds an MCP::Server for that key (its tools, its context) and answers with handle_json. Plain JSON responses, stateless, no server-to-client stream. No separate process to deploy; tenancy, scoping, rate limiting and security headers are the Admin API's, and the whole server is exercisable in a spec by handing it a JSON-RPC string.

  • Optional gem spree_mcp under spree/mcp (2026-09-15). Beside opentelemetry and dashboard, the precedent for optional top-level engines. spree_api does not take the mcp dependency; installs that do not want an MCP endpoint do not get one.

  • Generic writes work for every resource (2026-10-10; replaces the 2026-09-16 narrowing). create_resource / update_resource / delete_resource dispatch to the create, update and destroy operations, so the controller runs whatever workflow it declares. The refusal rule below existed only because the generic writes skipped workflows and would have been a second way to write the same record; dispatch makes them the same way. What is left for a dedicated tool is the non-CRUD member actions — cancel, complete, capture, fulfil, approve, activate — which is exactly the set of member-action endpoints. Fewer tools, one rule.

    The withdrawn text read: generic writes cover store, market, channel, delivery, payment and tax setup — resources whose controllers save the record directly — and a resource with a create or update workflow refuses the generic write and names the workflow tool instead, so there is exactly one way to write each thing. No task tools at 6.0; a composed tool is added only when usage shows a job spanning several workflows that the model fails to sequence.

  • Steps 1–5 ship as one pull request (2026-09-16). The "Order of operations" below proposed a registry-only PR first, with spree_mcp branching from main after it merged. Shipping the whole plan in one branch instead: the registry has no caller until the MCP adapter exists, so a registry-only PR asks reviewers to judge a contract against no consumer, and the second PR would re-open every shape question with the first already merged. Accepted cost: a large diff across spree_core, spree_api and a new gem. Mitigated by committing in the plan's phase order, so the history reads as the staged migration the plan describes.

  • The registry is copied out of feat/dash-assistant; that branch is not touched (2026-09-16). Files come across with git checkout feat/dash-assistant -- <path> so blame follows the code, then the three changes (rename, principal on the context, derived resource map) are applied here. Deleting the originals and repointing the RubyLLM adapter stays step 3 of the order of operations, for whoever owns that branch — it is a live worktree this run does not own.

  • No spree mcp command in @spree/cli at 6.0 (2026-09-15). The mounted Streamable HTTP endpoint serves every current client directly with a key in the client config; a stdio proxy or a config printer is a second thing to keep in step for no client that needs it today. Revisit when a client without HTTP transport matters.

Design Details

The agent-tool registry (spree_core)

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.admin_agent_tools — registered by class name, resolved on use
spree/core/lib/spree/agent_tools/context.rb   # {store, principal, ability, permission_keys}
spree/core/lib/spree/agent_tools/resource_map.rb
spree/core/lib/spree/agent_tools/record_summary.rb
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.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 signed-in admin and their ability. Over MCP the principal is a secret key. The context gains principal (an admin user or an API key) and permission_keys resolves from whichever it is: the ability's activated keys for a user, the key's expanded scopes for an API key. accessible(relation, action) still applies CanCanCan for a user principal; for a key principal the store scope is the whole tenancy answer, as it is in the Admin API today.

The resource map is derived, not hand-listed. Every admin controller already declares model_class, serializer_class and scoped_resource. Core owns the map's structure and the refusal for a model whose store scoping is accidental; spree_api fills it in its to_prepare by walking Spree::Api::V3::Admin::ResourceController descendants (eager-loaded in every environment for this purpose), the same way registries are filled after serializer classes load. The only fact a controller lacks is the dashboard path used in result links, kept as a small per-resource hash. The existing spec that compares map entries against controller declarations inverts into a spec that the derived map contains every controller.

Tool catalog

Tier Tools Parameters come from Offered to
Generic reads search_resources, get_resource, describe_resource The list and show operations; x-spree-filters for what can be filtered; admin serializers any read_* scope, filtered per resource
Reporting query_report, explain_report, describe_reporting, list_saved_reports, get_saved_report, save_report Spree.reporting registry (same source as the OpenAPI spec) read_reports + the per-subject scopes the reporting endpoints already check
Generic writes create_resource, update_resource, delete_resource The create, update and destroy operations' OpenAPI request schemas the operation's own write_* scope
Action tools one per non-CRUD member action: orders_cancel, orders_complete, fulfillments_fulfill, returns_approve, refunds_create, payments_capture, products_activate, … the member operation's OpenAPI request schema the operation's own scope
Generic record writes create_resource, update_resource, delete_resource Resource map; the controller's permitted attributes via the generated admin.yaml request schemas matching write_* scope, only for resources with no create/update workflow

describe_resource returns, for one resource: filterable fields and named scopes (reads), the writable attribute schema from the OpenAPI spec where the resource has no workflow, the workflow tools that take a record of this resource as their subject, status values from has_status, and for typed-subclass families the type shorthands from the family's types endpoint. The model discovers vocabulary instead of guessing it, and nothing is enumerated by hand in a tool description.

search_resources results are compact by design: a summary line, the prefixed id, a dashboard link, and only the fields the caller asked for. MCP results land in the model's context window verbatim, so an admin serializer's full payload is the wrong default; get_resource is the full record.

Workflow tools

Superseded by step 6 (2026-10-10). This section describes how the first five steps derived a tool from a workflow's Ruby signature: YARD schema derivation, the row lock the adapter took, principal injection from the context, CONTEXT_PARAMETERS, UNCONVERTED_PRINCIPAL_PARAMETERS. Under dispatch the controller takes the lock, injects the actor from the credential and fills in the store, so all of that machinery is deleted. It is kept here as the record of what step 6 removes and why — not as instructions. The catalog's shape is in "the catalog is keyed by operation" under Key Decisions.

The allowlist. One file in core:

Spree.admin_agent_tools.expose_workflows(
  order_cancel_workflow: 'write_orders',
  order_complete_workflow: 'write_orders',
  fulfillment_create_workflow: 'write_orders',
  fulfillment_mark_delivered_workflow: 'write_orders',
  return_approve_workflow: 'write_returns',
  refund_create_workflow: 'write_orders',
  product_create_workflow: 'write_products',
  product_activate_workflow: 'write_products',
  # … the workflows the admin controllers call, minus internal ones
)

Keys are Spree::Dependencies keys, so the tool follows whatever class the host app has registered. The starting set is the 57 workflows the admin controllers called on 2026-09-16, minus those a controller reaches only indirectly or that exist for the platform rather than a merchant (invitation acceptance, customer anonymisation, payout sweeps). An entry may carry except: to hide a deprecated parameter (restock_items on cancel) and summary: to override the generated confirmation line.

Controllers are the reference wiring. For every exposed workflow there is an admin controller action that calls it, and that action defines how a request becomes keywords: which lookups are store-scoped (current_store.order_cancellation_reasons.find_by_prefix_id!), which principal is injected (canceler: try_spree_current_user), which lock is taken (with_order_lock). The adapter follows those rules generically rather than per tool, and a contract spec walks the admin controllers, collects every Spree.*_workflow they invoke, and fails when one is neither exposed nor named in an explicit exclusion list with a reason. The permission in the allowlist must equal the controller's scoped_resource write scope; the same spec checks it.

Schema derivation. Method#parameters on perform gives each keyword and whether it is required. The YARD @param name [Type] description lines above perform give the type and the description, parsed once at boot from the workflow's source and cached; 105 of 109 workflows document every parameter today, and the spec fails on an exposed workflow with an undocumented one. Type mapping:

  • A Spree model ([Spree::Order], [Spree::Fulfillment]) becomes a string parameter taking a prefixed id, resolved to a record through the resource map under the context's store (and the ability, for a user principal). A model the map does not know cannot be exposed; a value that does not resolve is a tool error naming the parameter.
  • String, Boolean, Numeric, BigDecimal, Time become the matching JSON primitives; Time is ISO 8601.
  • Hash and Array<Hash> pass through as objects, described by the parameter's doc text.
  • Principal parameters — canceler, approver, reviewer, created_by, refunder — are removed from the schema and injected from the context as context.actor: the admin user for a user principal, the API key for a key principal. 6.0-action-actors.md makes the key a valid actor on the order operations, so an MCP cancel records the key that did it; on associations not yet converted (6.1 in that plan) a key actor is dropped to nil by the adapter rather than raising, and the tool result says the change was unattributed.

Naming. The workflow key with dots replaced by underscores (orders.cancel → orders_cancel), because MCP tool names allow only letters, digits, underscore and hyphen. The description is the workflow class's leading comment, first paragraph.

Execution. The adapter takes the same row lock the controller takes for an order-subject workflow, calls the workflow, and shapes the result: on success a one-line summary ("Cancel order R123456789", generated from the workflow key and the subject record's summary line unless the allowlist overrides it) plus the returned record in its compact form; on failure a tool error carrying the record's errors or the result's error text, so the model can self-correct instead of retrying blind.

Count. About 50 workflow tools after exclusions. A key sees only the tools its scopes permit, so a key minted for order operations sees around twenty. If a client's list limit ever bites, the fallback is grouping a family behind one tool at the listing layer — the registry does not change.

Generic record writes

Superseded by step 6 (2026-10-10). The refusal rule below — a resource with a workflow refuses the generic write — existed because these writes assigned attributes and saved. Dispatched, update_resource is a PATCH and the controller runs its own workflow, so generic create, update and destroy are correct for every resource and the refusal goes.

Only for resources whose controller declares no create or update workflow: markets, channels, delivery methods and profiles, payment methods, tax categories and rates, roles, customer groups, allowed origins, store settings. Dispatched, these take exactly the path the API takes — the controller's own permitted_params, its own workflow where it declares one — and the summary is generated ("Update market EU: currencies EUR, PLN"). The refusal rule the step 1–5 build needed is gone: every resource is writable through these three, because every one reaches its controller. delete_resource is the same, whether the controller destroys through a workflow or directly.

What is not exposed at 6.0

  • The 17 Tier 1 services the controllers call for order editing, fees, discounts, addresses, stock levels and store credits. They arrive as workflows, not through a second adapter.
  • Task tools. Every one the first draft listed is one workflow (update_product_status → products_activate / products_draft / products_archive) or a generic write (create_export). The branch's update_product_status is retired; the import mapping proposal stays in the assistant because it needs the model.
  • Files. Media uploads, import files, label downloads. MCP carries text and structured content.
  • Money moves without a person. Refund and capture are workflow tools under write_orders, guarded by the key's scope and the client's confirmation only. The docs say plainly: an agent that should read orders but never refund gets a key without the write scope.

The MCP gem (spree/mcp, gem spree_mcp)

spree/mcp/
  app/controllers/spree/api/v3/admin/mcp_controller.rb  # POST /api/v3/admin/mcp → Server.for(key).handle_json
  lib/spree/mcp/engine.rb          # draws the route inside the admin API namespace
  lib/spree/mcp/server.rb          # builds an MCP::Server for one principal from the registry
  lib/spree/mcp/tool_adapter.rb    # Spree::AgentTool → MCP::Tool definition + handler
  spree_mcp.gemspec                # spree_core, spree_api, mcp ~> 1.5
  • Endpoint: POST /api/v3/admin/mcp, one JSON-RPC message per request, JSON response. Stateless: no session id, any Puma worker answers any request. The optional GET server-to-client stream is not offered at 6.0.
  • Authentication: the controller inherits the admin API's authenticate_secret_key! and store context, so the key selects the store and X-Spree-Store is honoured only when it matches the key's store, as today. JWT is refused: this is a machine surface. Rate limiting and security headers come with the base controller.
  • Per-request server: Spree::Mcp::Server.for(principal) builds an MCP::Server whose tool list is the registry filtered by the key's expanded scopes and whose server_context is the Spree::AgentTools::Context for that key. Building it is cheap (tool definitions are memoised per registry state); nothing is cached across principals.
  • Tool listing: tools/list returns the registry filtered by the key's expanded scopes (read_all / write_all expand as they do for the API). Listing is stable for a given key, so the 2026-07-28 cache hints apply. Tool annotations carry readOnlyHint for reads and destructiveHint for mutating tools, from the registry's mutating flag, so clients that gate confirmation on annotations do the right thing.
  • Tool calls: the adapter validates arguments against the tool's schema, builds the context from the key, runs the executor, and returns the result as structured content plus a text summary. A refusal from the executor ({error: …}) is a tool error, not a protocol error, so the model can self-correct — same rule as the CLI's 403 remediation text.
  • Resources and prompts: none at 6.0. describe_resource is a tool because clients handle tools uniformly and resources unevenly.

Permissions, end to end

  1. Minting decides what exists. An admin with write_api_keys mints a secret key and picks scopes, as for any integration. tools/list for that key contains only what those scopes permit; a tool the key cannot use is never named to the model.
  2. The key decides the store. Tenancy comes from the key, never from a parameter; every lookup runs through the store-scoped resource map, so another store's prefixed id is "not found".
  3. Every call re-checks the scope, so revoking or narrowing a key takes effect on the next call. Revocation stays the kill switch.
  4. The workflow decides whether the change is allowed and refuses in its own words, which the tool error carries back.
  5. The client asks the human. Claude Code prompts before each MCP tool call unless the user allowed that tool in settings; reads can be allowed once and writes left prompting. Mutating tools carry destructiveHint for clients that gate on annotations.

Attribution: with 6.0-action-actors.md, a workflow run over MCP records the API key as canceler / approver / created_by, so the order timeline reads "cancelled by WMS connector" rather than nothing. A key principal gets no record-level CanCanCan filtering, matching the Admin API's treatment of key requests today. Department- or seller-limited agents are the assistant's job with its signed-in user, or a later per-key ability. Not in scope, but cheap and worth a follow-up: an audit event per mutating tool call naming the key, which the Admin API also lacks for key requests.

How a client decides to use it

No command. The server's tools join the model's tool list with their names and descriptions and the model picks from the prompt. Three things make that reliable:

  • Descriptions and the server's instructions field. MCP lets a server send short usage guidance at discovery; ours says search first, describe_resource for vocabulary, then act.
  • Scope-filtered lists. A merchant key sees around twenty tools, not the catalog. Claude Code additionally defers large MCP tool lists and loads tools on demand.
  • The spree-cli skill draws the line for developer agents that have both a shell and the server: bulk, scripting and debugging go through spree api; conversational operations go through MCP.

Auth flow and where the key lives

  1. Mint. An admin with write_api_keys creates a secret key in the dashboard: a name that says which agent holds it ("Claude Code, orders"), and the scopes. The plaintext is shown once; only the digest is stored.
  2. Place. The client configuration carries the key as a request header on every call (see the per-client table). Nothing is exchanged or refreshed.
  3. Authenticate. Each request runs the Admin API's digest lookup. The key selects the store and the scopes. A missing, unknown or revoked key answers 401 with a JSON-RPC error whose text names the header to set and where to mint a key, because that text is what the model and the person read.
  4. Rotate or revoke in the dashboard; the next request fails and the client surfaces the error.
Client Where the key goes
Claude Code claude mcp add --transport http spree-admin https://<shop>/api/v3/admin/mcp --header "X-Spree-API-Key: sk_…" (user config); or a committed project .mcp.json referencing ${SPREE_API_KEY} so each developer exports their own key and none lands in git
Cursor .cursor/mcp.json: url plus a headers map
VS Code .vscode/mcp.json: type: http, url, headers, with a prompted secret input so the value is not stored in the file
Claude Desktop The connector UI accepts a URL and expects OAuth or no auth; until the OAuth lane ships, a stdio bridge that forwards the header
claude.ai Not a supported client until the OAuth lane ships
In-house agents Whatever HTTP client they use, with either header form

The docs page (Migration Path step 5) carries these snippets; the CLI config printer that would have generated them was deferred (Key Decisions).

How this differs from the Admin API CLI

Both surfaces exist because they serve different callers, not because one is the old way. The spree api command group stays the primary tool for developer agents.

spree api (CLI) MCP server
Caller Agents with a shell: Claude Code, Cursor, CI scripts, humans Clients that cannot shell out: Claude Desktop and claude.ai connectors, ChatGPT, Cursor's MCP panel, in-house agents; merchants who never open a terminal
Vocabulary Generic HTTP verbs plus endpoints / schema from the OpenAPI spec; the agent composes calls Curated tools with job-level semantics and generated schemas; the model picks a tool
Where results go Stdout; the agent decides what to read, can pipe to jq Straight into the model's context; results must be compact and summarised
Writes Anything the key's scopes allow, raw payloads One scope-gated tool per workflow with a derived schema; every write returns a human summary for the client's confirmation prompt
Setup Zero-config inside a project (auto-minted read key) A minted key in the client's MCP config; spree mcp (later) can print that config
Credentials Layered: flags, env, project auto-mint, profiles Secret key header now; OAuth 2.1 later
Coverage Every endpoint, by construction The catalog's tools, each naming an operation; a capability with no endpoint is an endpoint to add first
Substrate HTTP to the Admin API The same Admin API operations, dispatched in-process
Best at Bulk, scripting, debugging, anything the schema tools can express Conversational merchandising, reporting questions, guided setup

The rule of thumb for a developer agent: if it has a shell, spree api. The 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.admin_agent_tools: its Spree::Assistant::Tool and registry are deleted, its RubyLLM adapter reads the core registry, its context becomes a user-principal Spree::AgentTools::Context, and its approval gate keys off the same mutating flag. Chat persistence, streaming, provider integrations and the panel are untouched. What the assistant keeps that MCP does not have: server-side approval, record-level CanCanCan filtering for a signed-in admin, and result cards rendered from the same structured content.

Testing

No LLM anywhere in the suites: an MCP client is a JSON-RPC sender, so every layer is exercised with factories, real workflows and JSON strings. Four layers, each in the engine that owns the code, all run through pnpm test:rspec <engine>.

Core — registry and adapter units (spree_core). The tool DSL, registry, record summary and context specs move from the assistant branch. New:

  • Context with a key principal: permission_keys equals the key's expanded scopes (read_all expands), accessible applies no ability filter for a key and the existing record-level filter for a user.
  • Schema derivation against a workflow defined inline in the spec (required and optional keywords, a YARD block, a principal parameter, a deprecated one): required list, JSON types, description text, principal removed, except: honoured, a model-typed parameter rendered as a prefixed-id string, an undocumented parameter failing loudly.
  • Argument resolution: a prefixed id resolves within the context's store; another store's id and an unknown id return a tool error naming the parameter; a value of the wrong JSON type is refused before the workflow runs.
  • Execution through real workflows with factories: orders_cancel on a completed order cancels it and returns the summary line and compact record; on an order whose goods have shipped it returns the workflow's own refusal text as a tool error; the order-subject lock is taken (with_lock observed on the record). One such spec per workflow family (order, fulfillment, return, product, price list), not per workflow — the workflows have their own suites and the adapter is generic.
  • Generic record writes: an update on a market persists through validations, and so does one on a product — the controller behind it declares the workflow, so the generic write runs it. Ordinary create, update and destroy therefore have no dedicated tool of their own; a resource whose controller has no generic write (a variant, a fulfillment, a refund) keeps one.

API — contract specs (spree_api, where the controllers are).

  • Resource map derivation: every admin controller with a scoped_resource appears in the map with its model, serializer and permission; a controller whose model has accidental store scoping is refused at boot.
  • Allowlist contract: every Spree::Workflow subclass an admin controller invokes (collected by scanning the admin controller sources for Spree.<key> and resolving through Spree::Dependencies) is exposed or named in the exclusion list with a reason; every allowlist permission equals the invoking controller's scoped_resource write scope; every exposed workflow's model-typed parameters are resources the map knows.
  • A golden catalog: tools/list for a read_all + write_all key, serialised deterministically and committed under spec/fixtures. Any change to a workflow signature, a YARD line or the allowlist shows up as a diff in review, the way admin.yaml does for the REST surface. Regenerated with a rake task, never hand-edited.

MCP — protocol and endpoint (spree_mcp, own dummy app like spree_opentelemetry).

  • Adapter round-trip: a Spree::AgentTool becomes an MCP::Tool with a valid name, the derived input schema, and readOnlyHint / destructiveHint set from the mutating flag.
  • Server units with handle_json, no HTTP: server/discover answers the 2026-07-28 revision; tools/list for a key with read_products returns exactly the read tools for product-scoped resources and nothing mutating; tools/call on a read tool returns structured content; tools/call on a tool the key lacks the scope for is "tool not found", not "forbidden" (the tool was never offered); malformed arguments are a JSON-RPC invalid-params error with the parameter named.
  • Request specs against POST /api/v3/admin/mcp with create(:api_key, :secret, store:, scopes:) and the plaintext token in X-Spree-API-Key, as api_keys_controller_spec does: no key → 401; a JWT → 401; a key whose store differs from X-Spree-Store → 404; a well-formed tools/call on fulfillments_mark_delivered marks the fulfillment delivered end to end through the real workflow. Request specs, not controller specs: the endpoint is JSON-RPC, so the unit under test is the whole request, and render_views does not apply.

What is deliberately not tested here.

  • The workflows' behaviour — their own suites own it; the adapter specs assert only that the call reached the workflow with the right keywords and that its result was shaped correctly.
  • OpenAPI: the endpoint is JSON-RPC, excluded from swaggerize, documented on the docs page and by the golden catalog instead.
  • A live MCP client. The gem's own conformance is its maintainers' job; the QA environment from /project:implement-plan is where Claude Code is pointed at the endpoint by hand before the PR is opened.

scripts/test/ gains mcp in its engine list in the same PR that adds the gem, so pnpm test:changed picks its specs up.

Migration Path

  1. 6.0-action-actors.md lands first — ✅ merged 2026-09-16 (PR #14659); current_actor and the polymorphic order-operation actors are on main.

  2. Registry into core (spree_core): move the tool base class, registry, context, resource map and record summary from the assistant branch, renamed as above, with the principal abstraction. Derive the resource map from the controllers. Bring the branch's specs across. See "Taking the code from the assistant branch" below for exactly what moves and in what order.

  3. Reporting tools over Spree.reporting, reusing the reporting controller's member-level authorization for API keys.

  4. Workflow tools: the allowlist in core, the adapter (schema derivation, argument resolution, principal injection, locks, result shaping), the contract spec against the admin controllers, and the generic record writes for resources without a workflow. describe_resource gains the writable schema and the workflow tools per resource.

  5. spree_mcp gem: engine and route, the controller over handle_json, the adapter, the per-principal server; the protocol and request specs above, plus mcp in scripts/test/.

  6. Docs and skill: a docs/developer/agentic/admin-mcp.mdx page next to the docs-MCP page (setup per client, minting a key with the right scopes, what the tools are), and a cross-reference in the spree-cli agent skill saying when to reach for which.

  7. Execution through the Admin API (decided 2026-10-10, before merge). Steps 1–5 built the catalog and proved the protocol; this replaces how a tool call reaches the data. In order, each part shippable on its own:

    1. The dispatcher. Spree::AgentTools::ApiDispatch builds a Rack env for a method, path, query and body, forwards the caller's credential and Host, snapshots and restores Spree::Current around the call, and returns the parsed status, body and headers. Its specs are the contract: a nested call cannot see or corrupt the outer request's store, currency or locale, and a failing call returns the API's own error body rather than an exception.

    2. The catalog becomes data. Each entry names its operation (method and path template), its permission, its description, and which parameters it projects. The resource map keeps deriving the resource → controller mapping it already derives; what changes is that a tool holds a route rather than a model and a Ransack call.

    3. Reads move first. search_resources, get_resource and describe_resource dispatch to index/show. This alone fixes the prefixed-id filter, because the controller decodes ids — the fault is not patched, it stops existing.

    4. Writes follow, including the generic ones. The controller's permitted_params becomes the only writable-attribute list, so extension attributes work by construction and the hand-written lists go.

    5. The gaps become endpoints. Product curation and the stock upsert are reached directly today; they become Admin API endpoints and the tools point at them. Credential filtering (RecordSummary) stays — it guards what leaves for a model, which is not the API's job.

    6. Delete what the dispatcher replaced. The second scoping, the second permission check, the second error shape. The measure of this step is how much Ruby it removes.

      Built 2026-10-10. 415 lines deleted against 381 added, with the dispatcher itself counted in the additions. What went: the hand-written writable-attribute lists, the second store scoping in every read, the SERVICE_WRITTEN_MODELS list that withheld writes for fourteen models, the refusal rule that made a resource with a workflow unwritable generically, and the row-lock and actor-injection machinery the controller already performs.

      Two guards stayed, because the Admin API does not make them yet, and both are recorded rather than quietly kept: an unknown filter is named back instead of silently widening a search, and an attribute the controller does not permit is named instead of dropped behind a 200 that reports a change which never happened. Both go when strict filters and strict attributes land, and search_resources is three lines longer than before because of the first.

  8. Later, outside this plan: spree mcp stdio wrapper in @spree/cli that proxies to the mounted endpoint and prints client configs; a shopper-facing Storefront MCP (docs/plans/6.1-store-mcp-server.md). At 7 the catalog runs under TypeScript with @spree/admin-sdk, and the Ruby adapter is deleted rather than ported.

Taking the code from the assistant branch

The registry is lifted from feat/dash-assistant (unmerged) into a branch cut from main, and the assistant branch is then rebased to consume it. The lift happens first so the registry never exists in two places; merging the assistant first and extracting afterwards would carry RubyLLM into the history of a core contract and leave two copies to reconcile.

What moves, measured on the branch (2026-09-15):

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.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
registry subtotal 686
app/tools/spree/assistant/tools/*.rb (8 tools; update_product_status is retired, see below) 704 app/tools/spree/agent_tools/*.rb
spec/lib/spree/assistant/{resource_map,record_summary}_spec.rb, spec/tools/**, spec/authorization_spec.rb 546 spec/lib/spree/agent_tools/**, spec/tools/**

About 1,900 lines of Ruby including specs move; nothing is rewritten. The eight tools reference only the registry classes plus Spree::Export, Spree::ImportMapping and Spree::Products::Update, all already in core.

What stays on the assistant branch: the RubyLLM adapter, the turn loop, chat and message models, providers and integrations, controllers, serializers and their specs (about 2,300 lines), and the dashboard panel (about 1,800 lines of TypeScript). The assistant plan's phases are unaffected beyond the rebase.

Four changes made during the move, not after:

  1. Rename. Spree::Assistant::Tool → Spree::AgentTool, Spree::Assistant::Tools::X → Spree::AgentTools::X, Spree::Assistant.tools → Spree.admin_agent_tools. Tool names on the wire (search_resources, update_product_status, …) do not change: the assistant's persisted tool-call rows reference them.
  2. Principal on the context. Context.new(store:, user:) keeps working for the assistant; Context.new(store:, api_key:) is added for MCP. permission_keys resolves from the ability for a user and from Spree.permissions.expand_keys(api_key.scopes) for a key; accessible applies CanCanCan only for a user principal.
  3. Derived resource map. The hand-written ENTRIES list is replaced by a walk over Spree::Api::V3::Admin::ResourceController descendants, reading model_class, serializer_class and _scoped_resource. The dashboard paths become a per-resource hash the assistant contributes. The branch's "every entry matches its controller" spec inverts into "every controller with a scoped resource is in the map". The scoping refusal (UnscopedResourceError) is kept as is.
  4. update_product_status is retired. The products workflows (activate, draft, archive) become tools by the allowlist, so the hand-written tool would be a duplicate. Its spec's assertions on the summary line and the record-level authorisation check move to the workflow adapter's spec. create_export folds into create_resource on exports.

Order of operations:

  1. Cut feat/agent-tools from main. Copy the files above with git checkout feat/dash-assistant -- <path> and git mv them into place, so blame follows the code; apply the three changes; run the moved specs under pnpm test:rspec core.
  2. (Superseded 2026-09-16 by "Steps 1–5 ship as one pull request", and by step 6 shipping on the same branch before merge.) The original sequencing read: open the PR for step 1 alone. It is reviewable in isolation and has no MCP or LLM code in it.
  3. After it merges, rebase feat/dash-assistant onto main, delete the moved files from spree/assistant, point the RubyLLM adapter and RunTurn at Spree.admin_agent_tools and the core context, and run the assistant suite. The branch shrinks by the lines core gained.
  4. spree_mcp (step 4 of the Migration Path) starts from main once step 1 is in; it never branches from the assistant.

What the build changed against the design

Three things the design did not anticipate, recorded so the assistant rebase and any later adapter inherit them rather than rediscovering them:

  • Tenancy is injected like a principal. Several create workflows take store:, which is the credential's answer and not the caller's, so the adapter fills it from the context and never offers it. CONTEXT_PARAMETERS sits beside the principal list for exactly this.
  • The injected actor keywords come from acted_by, not a list. That macro already records every actor association per model so a sweep needs no list (Spree::ActedBy.models), and a hand-written list proved both over-broad and incomplete — it missed reviewed_by and reopened_by, which were therefore offered to callers. The four associations not yet converted to acted_by (6.1 in 6.0-action-actors.md) are named in UNCONVERTED_PRINCIPAL_PARAMETERS and drop off as they convert.
  • The derived map fills on first read, not in to_prepare. Deriving it eager-loads the application; doing that on every code reload would make every Spree developer pay a full load per file save for an optional feature. A resource served by two controllers under different scopes resolves to the narrower one and stays read-only, since the controllers do not agree on who may write it.

Constraints on Current Work

  • Do not add a tool that reads or writes a model directly (2026-10-10). A tool names an Admin API operation. A capability with no endpoint is an endpoint to add first, not a reason to reach past it — the dashboard rule, applied to agents.

  • Do not copy a guard from a controller into the agent layer. If the agent path needs it, the agent path is wrong: it should be running through the controller that already has it.

  • Do not add tool classes under Spree::Assistant::Tools on the assistant branch or anywhere else; new tools go under Spree::AgentTools once step 1 lands, and until then are held.

  • New admin controllers must declare model_class, serializer_class and scoped_resource (already the rule) — the derived resource map reads them, so an omission now hides a resource from every agent surface.

  • A new back-office write is an Admin API operation, added to the catalog or to the exclusion list in the same PR. The contract spec walks admin.yaml: every admin operation is either in the catalog or excluded with a reason, so a new endpoint cannot land unconsidered. Whether a service or a workflow sits behind it does not affect reachability.

  • A controller with a workflow must declare it through create_workflow / update_workflow, never a hand-written action. A hand-written action loses the record-level authorize_resource! the base class performs, and a dispatched tool call inherits whatever the controller does — so this matters more now, not less.

  • An operation's request body is documented in OpenAPI — that schema is what a tool offers a model, so an undocumented parameter is one no agent can use. Workflow YARD docs remain worth writing for their own readers; they no longer feed the tool schema, and the actor is injected by the controller from the credential rather than by the adapter.

  • Keep admin.yaml regenerated after Admin API changes; the writable schemas 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. 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 Questions

  • Does the Admin API itself expose an invitation's acceptance_url? RecordSummary withholds it from agents, and that is right — a link that mints a staff account should not reach an AI vendor. But if the endpoint returns it to any admin key, the agent filter is covering for an API that hands out a credential, and the fix belongs there. Worth a look on the API side, independently of this plan.

Nothing blocks implementation. One item is deliberately deferred:

  • OAuth 2.1 for hosted consumer connectors (claude.ai connectors, ChatGPT) — built alongside this, see 6.0-mcp-oauth. Key-based authentication reaches agents whose configuration a developer edits, and no further: every other way of carrying a header to a consumer client needs either a terminal or a single vendor's proprietary feature, so OAuth is what makes this a merchant feature rather than a developer one. The tool catalog, scope filtering and credential filter here are unchanged by it — a grant resolves into the same Spree::AgentTools::Context, narrowed to what the merchant approved.
  • A spree mcp CLI command (config printer or stdio proxy). A stdio bridge would let a desktop client reach this endpoint without OAuth, and is the common pattern among self-hosted platforms, but it needs Node and a hand-edited config file — so it serves the developer audience the CLI already serves better, not the merchant. Worth building only as a convenience for those clients, never as the answer to consumer reach.

References

  • docs/plans/5.5-admin-api-cli.md — CLI-first sequencing and the future-lanes table this plan executes
  • docs/plans/6.0-dashboard-assistant.md — the registry's origin; superseded on "No MCP in 6.0"
  • docs/plans/6.0-analytics-semantic-layer.md step 10 — the reporting tool shape
  • docs/plans/6.0-admin-rbac.md, docs/plans/5.5-admin-api-key-scopes.md — permission catalog and scopes
  • docs/developer/agentic/docs-mcp.mdx — the documentation MCP server, a sibling page
  • Official Ruby SDK: https://github.com/modelcontextprotocol/ruby-sdk (1.5.1; 2026-07-28 revision since 1.2.0)
  • MCP 2026-07-28 specification changelog: https://modelcontextprotocol.io/specification/2026-07-28/changelog