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.

19.7 KB
Raw Blame

Agent Tools from the Admin API Document

Status: In Progress — building the whole plan for the next 6.0 patch release Target: Spree 6.0.x (a 6.0 patch release); the 6.0.0 aliases end in 6.1, and expose_workflows is removed in 7.0 Depends on: 6.0-mcp-server.md (the agent-tool registry, in-process dispatch through the Admin API, and the 2026-10-10 decision that the catalog is keyed by operation, which this plan finishes) Author: Damian Legawiec (design driven with Claude) Last updated: 2026-11-03 Tracking: Linear V-3779 · GitHub —

Summary

Every Admin API write an admin key may call is an agent tool, with nothing to register. A tool is an operation in the Admin API's OpenAPI document. Its name is the resource and the action (orders_cancel), its description is the operation's summary and description, its input schema is the operation's path parameters and request body, and its permission is the controller's write scope. Core reads its own admin.yaml. An extension generates the same document from its own rswag specs, ships it in its gem, and Spree merges it in, so an extension's endpoints become tools the same way core's do, and the extension has a file to build its own API docs or client from.

Today a workflow becomes a tool only when it is listed in expose_workflows under a Spree::Dependencies key. Its schema is read from perform's signature and YARD block, and its endpoint is found by scanning controller source for Spree.<key>. An extension therefore has to register a dependency key, expose it, call it through that exact spelling, and hope the body keys it sends match the endpoint's. Three of those steps fail silently. An extension tool sent empty bodies until a fallback was added. A workflow called any other way ran in process instead of through its endpoint. Parameter names that differ between perform and the request body were bridged by guessing at suffixes. spree/spree#15083 patched each of these and was closed in favour of this plan: the patches made a mechanism with an end date harder to remove.

Key Decisions (do not deviate without discussion)

  • One tool per non-CRUD write operation (2026-11-03). Every POST, PATCH, PUT and DELETE operation in the document that is not a resource's plain create, update or destroy becomes a named tool: cancel, complete, capture, approve, send, request payment. CRUD stays with the generic create_resource, update_resource and delete_resource tools, which gain parent_id for resources nested under another record. A key is offered only the tools its write scopes permit.
    • Accepted trade-off: core has 96 such operations, so a key holding every write scope sees roughly a hundred tools, about fifty thousand tokens on a client that does not defer-load tools.
    • Rejected: a single run_action tool with per-resource action schemas in describe_resource. Every write would take two calls against a loose schema, and the client could only confirm "run_action".
    • Partly supersedes 6.0-mcp-server.md's "Never one tool per endpoint" (2026-09-15). Generic reads, generic writes and reporting still cover the hundreds of CRUD and read operations; only the actions get a tool each.
  • Writes only; custom reads opt in (2026-11-03). Core's 39 custom GET operations are mostly type vocabularies, which already reach agents through describe_resource, and file downloads, which MCP cannot carry. A GET operation becomes a tool only when its spec opts it in, as an extension's /quotes/statuses might.
  • The OpenAPI document is the only source (2026-11-03). Name, description, parameters and body schema all come from the operation, never from Ruby signatures, YARD comments or controller source.
    • Rejected: the comment above the controller action, which would be a second, weaker copy of the summary and description the rswag spec already writes and reviews on every API change.
    • Rejected: a description: on request_params, which is a second description per action.
    • Core already ships openapi/admin.yaml in the spree_api gem, and the agent tools already read it for write bodies, so nothing new is parsed at runtime. This is the 2026-10-10 MCP decision "the catalog is keyed by operation", finished.
  • Extensions generate and ship their own document (2026-11-03). An extension writes rswag integration specs for its admin endpoints. It generates openapi/admin.yaml with the rake task core uses, from a shared helper spree_api ships, and lists the file in its gemspec. Spree merges every loaded engine's openapi/admin.yaml into the document the catalog reads.
    • Accepted cost: an extension adding admin endpoints writes rswag specs for them. Enterprise has none today.
    • Rejected: deriving extension tools from request_params. That would mean two derivation paths, and extensions would get no published docs or SDK types.
  • Exposure is opt-out (2026-11-03). An operation is a tool unless its spec marks it otherwise with a stated reason (x-spree-agent: false plus x-spree-agent-reason). The endpoint already enforces authentication, the write scope, store scoping and the record-level ability, so an operation safe for an API key is safe for an agent holding the same key. Supersedes 6.0-mcp-server.md's "Exposure is an allowlist in core, keyed by dependency key" (2026-09-16). The DefaultCatalog::WORKFLOWS and EXCLUDED_WORKFLOWS lists go.
  • Ships in a 6.0 patch release (2026-11-03). main is still the 6.0 line, and patches already carry additive features (#15075, #15078). Four parts change shipped 6.0.0 behaviour, so each keeps the old behaviour working through 6.0.x under the "deprecate, never remove" rule:
    • Parameter names. Schemas now come from the request body, so orders_cancel takes cancel_reason_id, not reason. A fixed table of the 6.0.0 tools' old parameter names, generated once from their 6.0.0 schemas, maps each to its body field. An old name is accepted with a deprecation note in the result until 6.1. The table is explicit, not the suffix guessing this plan removes.
    • expose_workflows is deprecated (next decision).
    • Tool names that change are aliases until 6.1 (below).
    • New tools under existing scopes. Opt-out exposure offers a key actions an agent could not reach before. The API already let that key call them, so no permission widens, but the 6.0.x release notes list the new tools per scope.
  • expose_workflows is deprecated (2026-11-03; amended for 6.0.x the same day; corrected after build). It shipped in 6.0.0, so it is kept: the call is accepted and logs a deprecation, and changes nothing else. A workflow behind a documented endpoint is already that endpoint's tool, so it stays offered; only an exposed workflow whose endpoint has no operation in any document stops being offered, and the warning says what to ship instead. It is removed in 7.0. Offering the undocumented ones would have meant keeping the controller-source scanner, which is the interim state this plan removes.
    • Every workflow core exposes today is already behind an endpoint, except product activate, archive and draft, which get member endpoints in this plan.
    • Accepted cost: an extension tool exposed this way disappears until its endpoint is documented in an openapi/admin.yaml the gem ships. The 6.0.x release notes say so, since it is a change in a patch release.
    • Rejected: keeping exposed workflows running in process until 7.0. It would keep WorkflowTool, WorkflowSchema and principal injection alive for a release.
  • Tool names stay stable (2026-11-03). A tool is named after the controller's resource key and the route's action (orders_cancel, seller_requirement_submissions_accept, shipping_labels_refund). The derivation, checked against today's catalog, keeps 32 of the 41 workflow tool names: 29 now, and the three product status tools once their endpoints exist.
    • Aliases until 6.1. The other 6.0 names are resolvable aliases until 6.1, not listed in tools/list. Saved assistant tool calls replay, and a client that cached one still calls it. These are the ones that pointed at a CRUD create (fulfillments_create, refunds_create, variants_create, variants_update, purchase_orders_receive, stock_transfers_receive, shipping_labels_purchase, seller_requirement_submissions_waive) or carried the workflow's name rather than the route's (deliveries_update_tracking).
    • Explicit names. An operation may set operationId to name its tool explicitly, and a name the derivation would collide on must. On a create, an operationId also makes it a listed tool: receiving stock against a transfer or a purchase order, and purchasing a shipping label, are creates of a resource that lives under two parents, so the generic create cannot choose between them. Those keep their 6.0.0 names (stock_transfers_receive, purchase_orders_receive, shipping_labels_purchase).
    • deliveries_update_tracking no longer answers. 6.0.0 sent it to the mark-delivered endpoint and dropped its tracking fields, and no endpoint sets a carrier status, so keeping the name would keep marking deliveries delivered on a call meant to record tracking.
  • Spree::Dependencies is untouched, and the agent layer stops reading it (2026-11-03). Dependency keys remain the way a host app replaces a core class. An extension does not need one for its workflows to reach agents, and Dependencies.register is not added.

Design Details

The merged document

Spree::Api::AdminDocument loads spree_api's admin.yaml and the openapi/admin.yaml of every loaded engine that has one, merges their paths and components, and memoizes the result. It is lazy, as the current reader is, so an installation with no agent client never parses it.

An operation or component defined differently by two documents is logged at load, naming both engines, and the later definition is left out; the contract spec fails on any conflict. A silent override would let one gem replace another's operation, and raising would take every tool down with one stale document. A file that is not an OpenAPI document is ignored the same way.

The same merged document serves describe_resource's writable schemas and the generic tools' body checks, so AgentWriteSchemas reads from it instead of from core's file alone.

Building a tool from an operation

Spree::AgentTools::OperationTool replaces WorkflowTool. A tool class is built, and cached, for each operation the catalog includes:

  • Name: the operation's operationId when set. Otherwise <resource>_<action>, where the resource is the routed controller's resource-map key and the action is the route's action.
  • Description: the summary, then the description's first paragraph.
  • Permission: the routed controller's scoped_resource write scope.
  • Mutating: true, and every write keeps the destructive_hint 6.0.0 gave it, so no client confirms a call more loosely after the patch.
  • Input schema: the path parameters and the request body, as JSON Schema.
    • Each path parameter becomes a string carrying a prefixed id: id for the subject, order_id for the parent. A parent segment is optional: left out, it is read off the record the call names (a payment's order), under the caller's store and only through a resource the caller may read.
    • The request body's schema is used as it is, with nested properties, items, enum, required and per-field descriptions. Today a Hash reaches the client as a bare object; with the full schema a client can validate before calling.
    • $refs are inlined, and OpenAPI's nullable becomes a JSON Schema type list, so the tool schema stands alone.
    • What the body requires stays in the schema for clients, but the tool checks only the path it has to build. The endpoint refuses a missing field in its own words, which is the rule 6.0-mcp-server.md sets against copying a controller's guard into the agent layer.
  • Call: the path is filled from the arguments, each value percent-encoded so a ? or / stays inside its segment. The rest of the arguments travel as the body under the names the document gives them. There is no mapping step, because the schema and the body are the same document. The call is dispatched through ApiDispatch, as today.
  • Summary line: the operation summary and the subject's label from the response (Cancel an order R123456789). Before the call, the approval card shows the summary and the ids given.

The route lookup, from operation to controller, reads Spree::Core::Engine's routes, as the resource map already does. An operation whose route does not resolve, or whose controller declares no scoped resource (sign-in, setup, OAuth), is left out. So is every action of a controller whose model the resource map withholds for carrying a credential (API keys, integrations, webhook endpoints, gift cards, invitations): their responses carry the secret.

The 6.0.0 names that are no longer derived answer tools/call without being listed. Spree::Mcp::Server::AdminServer adds them to the tools the MCP gem looks a call up in, and Registry#find_for resolves them for any other adapter.

What the document carries for agents

rswag specs gain one helper, agent_tool, in spree_api's testing support, used by core and extensions, beside rswag's own operationId:

patch 'Cancel an order' do
  agent_tool false, reason: 'Wizard-only step'   # x-spree-agent: false
  agent_tool true                                 # opt a GET in
  operationId 'orders_cancel'                     # only when the derived name collides
end

Nothing else is added. The summary and description operations already carry become the tool's prose.

For an extension to generate its own document, request_body_for, admin_scope and the reproducible-run setup move from core's spec support into the gem (spree/api/testing_support/openapi), with Spree::Api::TestingSupport::Openapi.configure for the extension's swagger helper and a spree:openapi:generate rake task.

Generic tools

search_resources, get_resource, create_resource, update_resource and delete_resource take parent_id for a resource whose route runs under another record. An order's items, discounts and fees, a promotion's rules, and a product's variants become reachable through their own routes.

A call without it gets the refusal #15079 added, which names the parent and how to write through it. That refusal also tells the agent to pass the parent's id as parent_id where one parent id fills the route. describe_resource names the parent as a resource key, and lists the resource's action tools by name.

Product status endpoints

PATCH /api/v3/admin/products/:id/activate, /archive and /draft, each running its workflow, with rswag specs. They become products_activate, products_archive and products_draft, the names those tools already have.

What is deleted

  • Spree::AgentTools::WorkflowTool and WorkflowSchema, with their principal and context injection lists.
  • WorkflowEndpoints and Spree::Api::AgentWorkflowEndpoints, the controller source scanner.
  • What reads DefaultCatalog::WORKFLOWS and EXCLUDED_WORKFLOWS. The constants themselves stay through 6.0.x, deprecated with Ruby's deprecate_constant, so a reference to them does not break in a patch.
  • The YARD-driven half of agent_tools_contract_spec.rb.

Workflows keep their YARD blocks for their own readers. Hand-written Spree::AgentTool subclasses stay, for anything that is not an Admin API operation (reporting, imports).

Contract spec

spree_api ships a shared example that core and each extension include:

RSpec.describe 'agent tools', type: :contract do
  it_behaves_like 'an engine whose admin writes are agent tools', SpreeEnterprise::B2B::Engine
end

It fails when:

  • an admin write route of the engine has no operation in the engine's document;
  • an operation is opted out without a reason;
  • two operations derive the same tool name;
  • a tool name is not one MCP accepts;
  • an included operation has no summary, or names a permission the catalog does not know.

Whether the committed document matches a fresh rswag:specs:swaggerize is not checked here: generation runs the whole integration suite, so it stays the developer's step, as it is for core today.

Migration Path

  1. Merged document. Add Spree::Api::AdminDocument, and point AgentWriteSchemas at it. Add the generation helper and rake task extensions call, with a docs page.
  2. Product status endpoints with rswag specs, so every currently exposed workflow is behind an operation.
  3. OperationTool and catalog derivation from the document: names, aliases, permissions, input schemas, dispatch, summary lines. Ship the agent_tool rswag helper. Mark core's opt-outs with reasons, taken from today's EXCLUDED_WORKFLOWS.
  4. Generic tools take parent_id, with percent-encoded path values and the parent named in describe_resource and in the refusal.
  5. Deprecate expose_workflows to a warning. Add the old parameter-name table. Delete WorkflowTool, WorkflowSchema, WorkflowEndpoints, AgentWorkflowEndpoints and the catalog lists.
  6. The shared contract spec, run in core's suite.
  7. Docs. Rewrite docs/developer/mcp/custom-tools.mdx: add an admin endpoint with an rswag spec, and it is a tool. Update mcp/tools.mdx with the full list, and the spree/AGENTS.md "MCP and agent tools" rules.

All seven steps ship together in one PR for the 6.0 patch, committed in this order: keeping both catalogs would be the interim state this plan avoids. The release notes list the tools each write scope newly offers. 6.1 drops the parameter and name aliases, and 7.0 removes expose_workflows.

Constraints on Current Work

  • Do not add expose_workflows entries or Spree::Dependencies keys to reach agents. A back-office write that agents need is an Admin API operation with an rswag spec, and it becomes a tool when step 3 lands. Core workflows added before then still go into DefaultCatalog::WORKFLOWS, so they are not unreachable meanwhile; they move with the rest.
  • Every admin write operation gets a summary and a description written for someone choosing it. They become the tool's description: say what it does and when to use it, not how.
  • Extensions adding admin endpoints write rswag integration specs for them now, so their document exists when the merge lands. Enterprise's quote endpoints are the first case.
  • Name a member action after what it does to the record (cancel, request_payment), because the route's action becomes the tool name.

Open Questions

None block implementation. One is deferred:

  • Does a full-access key's tool count bite on a client in use? About a hundred tools on a key holding every write scope. Measure on the clients the MCP docs list once step 3 lands. Grouping a family behind one tool at the listing layer stays the fallback, as 6.0-mcp-server.md already notes, and it does not change the catalog.

References

  • docs/plans/6.0-mcp-server.md — the registry, dispatch, and the 2026-10-10 operation-keyed catalog decision this plan finishes; superseded on the allowlist and partly on "never one tool per endpoint"
  • spree/spree#15083 — closed: dependency keys for extensions, parent_id, and the controller body fallback; parent_id and path encoding carry over
  • spree/spree#15079 — the nested-resource refusal the generic tools keep
  • spree/AGENTS.md "MCP and agent tools" and "Request bodies are flat and declared with request_params"