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
Auto-discoverability of new agent tools for MCP server (V-3779) (#15086)
Damian Legawiec3e1c2bdeb614
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex 3d6b83f7ae..17b4c9d7f0 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -3916,6 +3916,7 @@ paths:summary: Reposition a category producttags:- Categories+ operationId: categories_reposition_productsecurity:- api_key: []bearer_auth: []@@ -6081,6 +6082,9 @@ paths:"$ref": "#/components/schemas/ErrorResponse""/api/v3/admin/customers/{id}/anonymize":post:+ x-spree-agent: false+ x-spree-agent-reason: Irreversible erasure of a person's data under GDPR Art.+ 17, which is not something to offer a model behind one confirmation prompt.summary: Erase a customer's personal datatags:- Customers@@ -7746,6 +7750,7 @@ paths:label: Spree CLIsource: spree api post /customers/{customer_id}/tax_identifiers/{id}/validate-d '{ ... }'+ operationId: customer_tax_identifiers_validatesecurity:- api_key: []bearer_auth: []@@ -22208,6 +22213,7 @@ paths:label: Spree CLIsource: spree api patch /orders/{order_id}/returns/{return_id}/labels/{id}/refund-d '{ ... }'+ operationId: return_labels_refundsecurity:- api_key: []bearer_auth: []@@ -24590,6 +24596,9 @@ paths:required: true"/api/v3/admin/prices/bulk_destroy":delete:+ x-spree-agent: false+ x-spree-agent-reason: Deletes many prices in one call behind a single confirmation;+ delete_resource removes them one at a time.summary: Bulk-delete pricestags:- Pricing@@ -26325,6 +26334,10 @@ paths:"$ref": "#/components/schemas/Product""/api/v3/admin/products/bulk_status_update":post:+ x-spree-agent: false+ x-spree-agent-reason: Writes the status column for many products at once, skipping+ the status workflows and their events; products_activate, products_archive and+ products_draft run them.summary: Bulk-update product statustags:- Products@@ -26884,6 +26897,9 @@ paths:required: true"/api/v3/admin/products/bulk_destroy":delete:+ x-spree-agent: false+ x-spree-agent-reason: Deletes many products in one call behind a single confirmation;+ delete_resource removes them one at a time.summary: Bulk-delete productstags:- Products@@ -42593,6 +42609,7 @@ paths:summary: Reposition a collection producttags:- Collections+ operationId: collections_reposition_productsecurity:- api_key: []bearer_auth: []@@ -44977,6 +44994,7 @@ paths:summary: Re-check a company tax registrationtags:- Companies+ operationId: company_tax_identifiers_validatesecurity:- api_key: []bearer_auth: []@@ -50557,6 +50575,7 @@ paths:summary: Buy or record a shipping labeltags:- Shipping Labels+ operationId: shipping_labels_purchasesecurity:- api_key: []bearer_auth: []@@ -53000,6 +53019,7 @@ paths:summary: Book in a deliverytags:- Purchase Orders+ operationId: purchase_orders_receivesecurity:- api_key: []bearer_auth: []@@ -53631,6 +53651,9 @@ paths:required: true"/api/v3/admin/reporting/query":post:+ x-spree-agent: false+ x-spree-agent-reason: query_report runs this query, with describe_reporting+ to learn the vocabulary first.summary: Run a reporting querytags:- Reports@@ -56575,6 +56598,9 @@ paths:schema:type: stringpatch:+ x-spree-agent: false+ x-spree-agent-reason: Settles a payout against the payment provider, reconciling+ against provider state an agent cannot see.summary: Mark a payout paidtags:- Sellers@@ -56893,6 +56919,9 @@ paths:- meta"/api/v3/admin/stock_levels/bulk_upsert":post:+ x-spree-agent: false+ x-spree-agent-reason: set_stock calls this endpoint already, taking stock by+ SKU and location the way a merchant names them.summary: Bulk-upsert stock levelstags:- Stock@@ -58427,6 +58456,7 @@ paths:summary: Count a delivery intags:- Stock Transfers+ operationId: stock_transfers_receivesecurity:- api_key: []bearer_auth: []diff --git a/docs/developer/mcp/custom-tools.mdx b/docs/developer/mcp/custom-tools.mdxindex 7f835a4ec1..d2e6b63eca 100644--- a/docs/developer/mcp/custom-tools.mdx+++ b/docs/developer/mcp/custom-tools.mdx@@ -1,22 +1,114 @@---title: "MCP Server Custom Tools"sidebarTitle: Custom tools-description: "Add your own tools to the MCP server, or expose a workflow your extension already ships."+description: "Your admin endpoints become MCP tools on their own. Add a tool by hand only for something that is not an endpoint."----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. Anything in it 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.+## Your admin endpoints are already tools-**A back-office operation you already have as a workflow.** Name its `Spree::Dependencies` key and the permission that should gate it:+Every documented Admin API action is an agent tool: cancel, approve, send, capture, anything that is not a plain create, update or destroy (those go through `create_resource`, `update_resource` and `delete_resource`). The exceptions are an action its spec opts out, a custom read its spec does not opt in, and the actions of a controller whose records carry credentials (API keys, webhooks, gift cards). Nothing registers a tool. Each is built from the endpoint's OpenAPI operation:-```ruby server/config/initializers/spree.rb-Spree.admin_agent_tools.expose_workflows(supplier_sync_workflow: 'write_purchasing')+| Tool | Comes from |+| --- | --- |+| Name | The resource and the action: `PATCH /quotes/:id/send` is `quotes_send`. An `operationId` overrides it, and also makes a create that is really an action, such as receiving stock against a transfer, a tool of its own. |+| Description | The operation's summary, then the first paragraph of its description. |+| Arguments | The path segments (`id`, and a parent such as `order_id`) beside the request body, under the names the endpoint documents. |+| Permission | The controller's `scoped_resource` write scope. |++So adding an endpoint and documenting it is the whole change. A call runs through the endpoint, with its authentication, scope check, record-level permissions and workflow, so an agent gets exactly what an API client gets. Write the summary and description for someone choosing the operation: they are what the model reads.++Core reads its own `admin.yaml`. Your application, and each extension, generates the same document from its own rswag specs at `openapi/admin.yaml`, and Spree merges every one into the document the tools read. Spree's own API reference and SDKs are built from core's document only; an app or extension that publishes docs or a typed client builds them from its own file.++### Documenting your application's endpoints++A new project from `create-spree-app` is set up already: `server/spec/swagger_helper.rb` and the contract spec come with it. In an older project, the generator adds them:++```bash+spree generate spree_dev_tools:openapi+```++It writes the swagger helper and the contract spec below. It also writes a skipped skeleton rswag spec for every admin action your controllers serve that is not documented yet, so what is left is each operation's description and the records its response is tested against. Run it again after adding endpoints; it only writes what is missing.++Write each spec the way the example below does, then generate the document and commit it:++```bash+spree task openapi:generate+```++### Documenting your extension's endpoints++An extension runs the same generator and task from its own directory, against its dummy app:++```bash+bundle exec rails g spree_dev_tools:openapi+bundle exec rake spree:openapi:generate+```++The task comes with `spree/testing_support/extension_rake`, which your Rakefile already requires. A gemspec that ships `git ls-files` includes the committed `openapi/admin.yaml` already. One that lists its files needs `openapi/*.yaml` added:++```ruby my_extension.gemspec+s.files = Dir['{app,config,db,lib}/**/*', 'openapi/*.yaml', 'LICENSE', 'README.md']+```++### Writing the specs++Document each admin endpoint the way core does:++```ruby spec/integration/admin/supplier_syncs_spec.rb+require 'swagger_helper'++RSpec.describe 'Supplier syncs', type: :request, swagger_doc: 'openapi/admin.yaml' do+ path '/api/v3/admin/suppliers/{id}/sync' do+ parameter name: :id, in: :path, type: :string, required: true, description: 'Supplier ID'++ post 'Sync a supplier' do+ tags 'Suppliers'+ admin_operation :write, :purchasing, description: <<~DESC+ Pulls the supplier's current catalogue and stock. Use it before raising a+ purchase order, so the order uses today's prices.+ DESC+ request_body_for++ response '200', 'synced' do+ # ...+ run_test!+ end+ end+ end+end+```++`admin_operation` sets what every admin operation repeats: the content types, the API key and bearer token headers, the scope note in the description, and a signed-in admin and secret key to call it with. A response block overrides either credential with its own `let`.++`request_body_for` documents the body from the controller's `request_params` declaration, so the tool's arguments, the API reference and the SDK types all come from the one declaration that also permits the request.++### Keeping an action out++An action that should not be offered to agents says so in its spec, with the reason. Irreversible erasure, platform jobs and wizard steps qualify; "not done yet" does not.++```ruby+post 'Erase a supplier' do+ agent_tool false, reason: 'Irreversible, and the supplier contract requires a person to confirm.'+end```-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.+A read is not a tool unless its spec opts it in, because most custom reads are type lists, which `describe_resource` already covers, or file downloads:-**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+get 'List supplier statuses' do+ agent_tool true+end+```++### The contract spec++`spec/agent_tools_spec.rb`, which the generator writes, fails when a new admin action lands undocumented, an opt-out lands without its reason, or two actions claim one tool name. Keep it in your suite.++## Something that is not an endpoint++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.rbmodule MyShop@@ -54,6 +146,10 @@ Four things worth knowing when you write one:A tool is offered only to a credential holding its `permission`, so a key that cannot read purchasing never learns `supplier_stock` exists.+<Note>+ `Spree.admin_agent_tools.expose_workflows` is deprecated and has no effect: an exposed workflow behind a documented endpoint is already that endpoint's tool, and one whose endpoint is not in any OpenAPI document is not offered. It is removed in 7.0. Tool names and parameters from 6.0.0 that changed keep answering through 6.0.x, and a call that uses one says what to send instead.+</Note>+## Which registryThere is one registry per surface, named the way the authentication strategies are:@@ -77,7 +173,7 @@ end<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 title="Admin API" icon="code" href="/api-reference/admin">+ The operations the action tools are built from.</Card></CardGroup>diff --git a/docs/developer/mcp/quick-start.mdx b/docs/developer/mcp/quick-start.mdxindex 33e5afe3da..2b17c88628 100644--- a/docs/developer/mcp/quick-start.mdx+++ b/docs/developer/mcp/quick-start.mdx@@ -151,7 +151,7 @@ Just ask it. It can list everything it reaches, and your assistant's own setting<CardGroup cols={2}><Card title="Tool reference" icon="wrench" href="/developer/mcp/tools">- All 58 tools and the permission each needs.+ The tools that ship with the server, and the permission each needs.</Card><Card title="Permissions and consent" icon="shield-check" href="/developer/mcp/permissions">What you approve, and what is out of reach whatever you do.diff --git a/docs/developer/mcp/tools.mdx b/docs/developer/mcp/tools.mdxindex 88734851a8..f3e3271552 100644--- a/docs/developer/mcp/tools.mdx+++ b/docs/developer/mcp/tools.mdx@@ -4,9 +4,9 @@ sidebarTitle: Toolsdescription: "Every tool the MCP server offers, what it is for and which permission it needs."----58 tools ship with the server. An assistant is only ever shown the ones you approved, so a connection for products alone sees roughly a dozen.+100 tools ship with the server: 17 general ones, and one for each action the Admin API offers — cancel an order, capture a payment, approve a seller. An assistant is only ever shown the ones you approved, so a connection for products alone sees a fraction of them.-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).+The catalog is not a mirror of the API's 500-odd operations. Plain reads and writes of a record go through the generic tools under [creating, changing and deleting records](#creating-changing-and-deleting-records), and each [action](#actions) is a tool of its own, built from the Admin API operation it runs.<Note>The **Permission** column is what you have to approve for the tool to be offered. A dash means it has no permission of its own and is checked per record instead: `search_resources` is offered to everyone, but only finds what you approved.@@ -33,68 +33,13 @@ The catalog is deliberately not a mirror of the API's 500-odd operations — a t| 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+### Stock| 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@@ -120,7 +65,6 @@ creating one in the dashboard does.| `create_resource` | — | write || `update_resource` | — | write || `delete_resource` | — | write |-| `tax_exemption_certificates_verify` | `write_customers` | write |The dash is the point: each call is gated on the resource being written, so aconnection approved for products can create a product and is refused a market.@@ -128,10 +72,185 @@ Call `describe_resource` for what a resource accepts.Some records exist only inside another: an order's items, discounts and fees.`describe_resource` names that record as the resource's `parent`, and each-generic tool that reads or writes a record takes its id as `parent_id`. That is-how an assistant changes a quantity, sets a negotiated unit price or adds a-discount on a draft order.+generic tool that reads or writes a record takes its id as `parent_id`. That is how an assistant changes a+quantity, sets a negotiated unit price or adds a discount on a draft order.++## Actions++Every Admin API action that is not a plain create, update or delete is a tool, named after the record and the action. Its description, its arguments and the permission it needs are the operation's own, so the [Admin API reference](/api-reference/admin) is the full description of each one. Every action is a write, and asks your client to confirm before it runs.++### Catalogs+| Tool | Permission |+| --- | --- |+| `catalog_quantity_rules_upsert` | `write_products` |+| `catalogs_activate` | `write_products` |+| `catalogs_assign` | `write_products` |+| `catalogs_deactivate` | `write_products` |+| `catalogs_import_products` | `write_products` |++### Categories++| Tool | Permission |+| --- | --- |+| `categories_reposition` | `write_categories` |+| `categories_reposition_product` | `write_products` |++### Channels++| Tool | Permission |+| --- | --- |+| `channels_add_products` | `write_settings` |+| `channels_remove_products` | `write_settings` |++### Collections++| Tool | Permission |+| --- | --- |+| `collections_reposition_product` | `write_products` |++### Companies++| Tool | Permission |+| --- | --- |+| `company_tax_identifiers_validate` | `write_customers` |+| `tax_exemption_certificates_revoke` | `write_customers` |+| `tax_exemption_certificates_verify` | `write_customers` |++### Customers++| Tool | Permission |+| --- | --- |+| `customer_tax_identifiers_validate` | `write_customers` |+| `customers_bulk_add_tags` | `write_customers` |+| `customers_bulk_add_to_groups` | `write_customers` |+| `customers_bulk_remove_from_groups` | `write_customers` |+| `customers_bulk_remove_tags` | `write_customers` |++### Deliveries++| Tool | Permission |+| --- | --- |+| `deliveries_mark_delivered` | `write_orders` |++### Fulfillments++| Tool | Permission |+| --- | --- |+| `fulfillments_cancel` | `write_fulfillments` |+| `fulfillments_fulfill` | `write_fulfillments` |+| `fulfillments_mark_delivered` | `write_fulfillments` |+| `fulfillments_split` | `write_fulfillments` |++### Orders++| Tool | Permission |+| --- | --- |+| `claims_approve` | `write_orders` |+| `claims_cancel` | `write_orders` |+| `claims_deny` | `write_orders` |+| `claims_resolve` | `write_orders` |+| `digital_links_reset` | `write_orders` |+| `exchanges_approve` | `write_orders` |+| `exchanges_cancel` | `write_orders` |+| `exchanges_fulfill` | `write_orders` |+| `exchanges_receive` | `write_orders` |+| `orders_approve` | `write_orders` |+| `orders_cancel` | `write_orders` |+| `orders_complete` | `write_orders` |+| `orders_resend_confirmation` | `write_orders` |+| `orders_resend_digital_links` | `write_orders` |+| `return_labels_refund` | `write_orders` |+| `returns_approve` | `write_orders` |+| `returns_cancel` | `write_orders` |+| `returns_receive` | `write_orders` |+| `returns_refund` | `write_orders` |++### Payments++| Tool | Permission |+| --- | --- |+| `payments_capture` | `write_payments` |+| `payments_void` | `write_payments` |++### Pricing++| Tool | Permission |+| --- | --- |+| `price_lists_activate` | `write_products` |+| `price_lists_deactivate` | `write_products` |+| `prices_bulk_upsert` | `write_products` |++### Product Types++| Tool | Permission |+| --- | --- |+| `product_types_apply_to_products` | `write_product_types` |++### Products++| Tool | Permission |+| --- | --- |+| `products_activate` | `write_products` |+| `products_approve` | `write_products` |+| `products_archive` | `write_products` |+| `products_bulk_add_tags` | `write_products` |+| `products_bulk_add_to_categories` | `write_products` |+| `products_bulk_add_to_channels` | `write_products` |+| `products_bulk_add_to_collections` | `write_products` |+| `products_bulk_remove_from_categories` | `write_products` |+| `products_bulk_remove_from_channels` | `write_products` |+| `products_bulk_remove_from_collections` | `write_products` |+| `products_bulk_remove_tags` | `write_products` |+| `products_bulk_status_update` | `write_products` |+| `products_clone` | `write_products` |+| `products_draft` | `write_products` |+| `products_reject` | `write_products` |++### Purchase Orders++| Tool | Permission |+| --- | --- |+| `purchase_orders_cancel` | `write_purchasing` |+| `purchase_orders_close` | `write_purchasing` |+| `purchase_orders_mark_draft` | `write_purchasing` |+| `purchase_orders_mark_ordered` | `write_purchasing` |+| `purchase_orders_receive` | `write_purchasing` |++### Sellers++| Tool | Permission |+| --- | --- |+| `invitations_resend` | `write_sellers` |+| `seller_requirement_submissions_accept` | `write_sellers` |+| `seller_requirement_submissions_reject` | `write_sellers` |+| `sellers_approve` | `write_sellers` |+| `sellers_invite` | `write_sellers` |+| `sellers_reject` | `write_sellers` |+| `sellers_reopen_onboarding` | `write_sellers` |+| `sellers_suspend` | `write_sellers` |++### Shipping Labels++| Tool | Permission |+| --- | --- |+| `shipping_labels_purchase` | `write_orders` |+| `shipping_labels_refund` | `write_orders` |++### Stock Transfers++| Tool | Permission |+| --- | --- |+| `stock_transfers_cancel` | `write_stock` |+| `stock_transfers_close` | `write_stock` |+| `stock_transfers_mark_draft` | `write_stock` |+| `stock_transfers_mark_in_transit` | `write_stock` |+| `stock_transfers_mark_ready` | `write_stock` |+| `stock_transfers_receive` | `write_stock` |++<Note>+ Tools named in Spree 6.0.0 that no longer appear here — `fulfillments_create`, `refunds_create`, `variants_create` and the like, which are now `create_resource` calls — still answer through 6.0.x, as do the 6.0.0 argument names. A call that uses one says what to send instead. `deliveries_update_tracking` no longer answers: in 6.0.0 it marked the delivery delivered and dropped its tracking fields.+</Note>## Resources@@ -152,7 +271,7 @@ Some things are out of reach whatever you approve.- **Erasing a customer.** GDPR erasure is irreversible and is not something to put behind a single confirmation prompt. Do it in the dashboard.- **Codes that spend money.** A gift card or coupon export carries live codes, so no tool creates or reads one. Download it from the dashboard.-25 further workflows are excluded for reasons a contract spec enforces, so one cannot be exposed by accident.+An action an assistant must not run is marked in the API reference with the reason. A contract spec fails when an admin action has no documented operation or an opt-out gives no reason.## Writing records@@ -173,6 +292,6 @@ Two things worth knowing about the generic writes:What you approve, and what an assistant can never reach.</Card><Card title="Custom tools" icon="puzzle-piece" href="/developer/mcp/custom-tools">- Add your own, or expose a workflow your extension ships.+ How your extension's admin endpoints become tools, and adding one by hand.</Card></CardGroup>diff --git a/docs/plans/6.0-agent-tools-from-openapi.md b/docs/plans/6.0-agent-tools-from-openapi.mdnew file mode 100644index 0000000000..1f1a17ced0--- /dev/null+++ b/docs/plans/6.0-agent-tools-from-openapi.md@@ -0,0 +1,361 @@+# 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.+ - `$ref`s 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`:++```ruby+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:++```ruby+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`"diff --git a/docs/plans/6.0-mcp-server.md b/docs/plans/6.0-mcp-server.mdindex 4e21dad349..3671f042da 100644--- a/docs/plans/6.0-mcp-server.md+++ b/docs/plans/6.0-mcp-server.md@@ -45,6 +45,9 @@ so a tool reaches data exactly the way any other client does.`spree_agents`: nothing intelligent runs in the registry, and a name thatpromised 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 twohundred plus tools, and the CLI plan already priced that (a ninety-three-toolserver costs roughly fifty-five thousand tokens of context; some clients cap@@ -67,6 +70,9 @@ 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).**+ *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 thedependency key means a host app that swaps `Spree.order_cancel_workflow`diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 7ff370271a..5e32898c8d 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -6708,3 +6708,14 @@ settings nav, search, slots, tables, translations) belongs in one of thoseplaces; anywhere else the build drops it once the flag lands. TipTap,CodeMirror and Recharts are imported only by their `dashboard-ui` component,which loads them on demand.++## 2026-11-03 — Agent tools come from the Admin API document, and extensions ship theirs++**Context:** An extension's workflow reached agents only through `expose_workflows` under a `Spree::Dependencies` key, with its schema read from `perform`'s YARD block and its endpoint found by scanning controller source for `Spree.<key>`. Building Enterprise quotes on it showed three silent failures: empty request bodies, workflows running in process when called another way, and parameter names bridged by guessing. spree/spree#15083 patched them and was closed: the 2026-10-10 MCP decision had already keyed the catalog on operations, and the patches deepened the dependency-key path instead.++**Decision:** Every non-CRUD write operation in the Admin API's OpenAPI document is an agent tool, opt-out with a stated reason; custom GET operations opt in. Name, description, path parameters and body schema come from the operation, and permission from the routed controller's write scope. Each extension generates `openapi/admin.yaml` from its own rswag specs and ships it in its gem; Spree merges every engine's document. CRUD stays with the generic tools, which take `parent_id` for nested resources. It ships in a 6.0 patch: `expose_workflows` is deprecated and has no effect (a workflow behind a documented endpoint is already that endpoint's tool), and is removed in 7.0. The 6.0.0 tools' renamed parameters and tool names stay accepted as aliases until 6.1. The agent layer stops reading `Spree::Dependencies`.++**Consequences:** A full-access key sees about a hundred tools. Extensions adding admin endpoints must write rswag specs for them. The 6.0.x release notes list the tools each write scope newly offers. Product activate, archive and draft get member endpoints. `WorkflowTool`, `WorkflowSchema`, the controller source scanner and the catalog allowlists are deleted.++**Plan:** `6.0-agent-tools-from-openapi.md`. **Plans amended:** `6.0-mcp-server.md` (allowlist keyed by dependency key superseded; "never one tool per endpoint" narrowed to CRUD and reads).+diff --git a/spree/AGENTS.md b/spree/AGENTS.mdindex f4362ff502..1784c209a6 100644--- a/spree/AGENTS.md+++ b/spree/AGENTS.md@@ -88,11 +88,11 @@ Admin serializers extend Store serializers; every serializer an Admin one refere**Every new back-office workflow or feature also ships in the MCP server** — anything a merchant can do in the admin dashboard or Admin API, an agent can do too. Tools live in `spree_core` (`Spree.admin_agent_tools`, `app/tools/spree/agent_tools/`), not in `spree_mcp`, so the dashboard assistant gets them as well (`docs/plans/6.0-mcp-server.md`).-- A new workflow goes into `Spree::AgentTools::DefaultCatalog::WORKFLOWS`, with the same write scope as the admin controller that runs it. Hide parameters an agent must not set with `except:`.-- Plain CRUD on a new resource goes through the generic `search_resources` / `get_resource` / `create_resource` / `update_resource` / `delete_resource` tools. These reach a resource only through its Admin API controller (`Spree::AgentTools::ResourceMap`), so a back-office resource needs one.-- Anything that is neither a workflow nor CRUD (reports, imports, files) gets its own `Spree::AgentTool` subclass, registered in `DefaultCatalog::TOOLS`.-- Leaving something out takes a stated reason in `EXCLUDED_WORKFLOWS`. Irreversible, platform-wide or wizard-only steps qualify; "not done yet" doesn't. `spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb` fails on a workflow in neither list, but it only scans controllers under `app/controllers/spree/api/v3/admin` — a workflow run from a controller concern (returns, claims, exchanges…) needs the same decision by hand.-- Tool descriptions are how an agent learns the feature: say what it does and when to use it. Update `docs/developer/mcp/tools.mdx` with the new tool.+- Every Admin API action that isn't plain create, update or destroy is a tool on its own, built from its OpenAPI operation (`docs/plans/6.0-agent-tools-from-openapi.md`): name from the resource and action, description from the summary and description, arguments from the path and request body, permission from the controller's `scoped_resource`. So a new back-office action needs an endpoint and an rswag spec, nothing else. Don't add `expose_workflows` calls (deprecated) or `Spree::Dependencies` keys to reach agents.+- Plain CRUD on a new resource goes through the generic `search_resources` / `get_resource` / `create_resource` / `update_resource` / `delete_resource` tools. These reach a resource only through its Admin API controller (`Spree::AgentTools::ResourceMap`), so a back-office resource needs one. A nested resource takes its parent's id as `parent_id`.+- Anything that is not an Admin API operation (reports, imports, files) gets its own `Spree::AgentTool` subclass, registered in `DefaultCatalog::TOOLS`.+- Leaving an action out takes `agent_tool false, reason: '…'` in its rswag spec. Irreversible, platform-wide or wizard-only steps qualify; "not done yet" doesn't. A custom GET is a tool only with `agent_tool true`. `spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb` fails on an admin action with no operation, an opt-out with no reason, or two actions deriving one tool name; give one an `operationId`.+- An operation's summary and description are how an agent learns the feature: say what it does and when to use it. Update `docs/developer/mcp/tools.mdx` with the new tool.## Emails (Liquid + MJML)diff --git a/spree/api/lib/spree/api/admin_document.rb b/spree/api/lib/spree/api/admin_document.rbnew file mode 100644index 0000000000..8bc1fc2e1a--- /dev/null+++ b/spree/api/lib/spree/api/admin_document.rb@@ -0,0 +1,275 @@+module Spree+ module Api+ # The Admin API's OpenAPI document as agents read it: core's `admin.yaml`+ # merged with the `openapi/admin.yaml` each extension ships in its gem.+ #+ # An extension documents its admin endpoints the way core does — rswag+ # integration specs, generated into a file — so its operations reach+ # agents, API docs and SDKs from the same contract. Nothing registers the+ # file: an engine that has one is read.+ #+ # Loaded once, lazily: core's document alone is well over a megabyte, and+ # an installation with no agent client should never pay for parsing it.+ #+ # See docs/plans/6.0-agent-tools-from-openapi.md.+ module AdminDocument+ # Where an extension keeps its generated document, relative to its root.+ EXTENSION_PATH = File.join('openapi', 'admin.yaml')++ HTTP_VERBS = %w[get post put patch delete head options].freeze++ class << self+ # @return [Hash] the merged document+ def document+ @document ||= load_document+ end++ # Operations or components two documents describe differently. The+ # first document keeps them — core's, then extensions in load order —+ # and the later one's are left out rather than silently replacing an+ # endpoint or failing every tool; the contract spec fails on any.+ #+ # @return [Array<String>]+ def conflicts+ document+ @conflicts+ end++ # Which document an operation came from, so a contract spec can check+ # an extension against its own operations only.+ #+ # @param path [String] the OpenAPI path, e.g. `/api/v3/admin/quotes/{id}/send`+ # @param verb [String, Symbol]+ # @return [String, nil] the engine's name, or `spree_api` for core+ def source_of(path, verb)+ document+ @sources[[path, verb.to_s.downcase]]+ end++ # Forgets the parsed document only when a document file changed, so a+ # code reload in development does not re-parse a megabyte of generated+ # YAML that no edit to Ruby could have changed.+ #+ # @return [void]+ def refresh!+ current = signature+ reset! unless current == @signature+ @signature = current+ end++ # Forgets the parsed document, so the next reader loads it again.+ #+ # @return [void]+ def reset!+ @document = nil+ @sources = nil+ @conflicts = nil+ end++ # Core's generated document: `docs/` in a source checkout, or the copy+ # the release packs into the gem. Resolved lazily: the engine class+ # does not exist yet while this file loads.+ #+ # @return [Pathname]+ def core_path+ source = Spree::Api::Engine.root.join('..', '..', 'docs', 'api-reference', 'admin.yaml')+ source.exist? ? source : Spree::Api::Engine.root.join(EXTENSION_PATH)+ end++ # Every other engine that ships a document, and the application+ # itself, which may add admin endpoints of its own.+ #+ # @return [Hash{String => Pathname}] engine name => document+ def extension_paths+ engines = Rails.application.railties.grep(Rails::Engine) + [Rails.application]+ engines.each_with_object({}) do |engine, paths|+ next if engine.is_a?(Spree::Api::Engine)++ path = engine.root&.join(EXTENSION_PATH)+ next unless path&.exist?+ next if path.expand_path == core_path.expand_path++ paths[engine.engine_name] = path+ end+ end++ # A request body is declared once per endpoint and published as a+ # component, so the operation carries a `$ref` to it rather than the+ # properties themselves. A body that builds on a shared shape is an+ # `allOf` of that shape and its own fields, read as one object.+ # Followed a few hops, which is as deep as the generated document+ # nests them.+ #+ # @param schema [Hash, nil] a schema that may be a reference+ # @return [Hash, nil] the schema it names+ def resolve_schema(schema, depth = 0)+ return unless schema.is_a?(Hash)+ return if depth > 3+ return merge_all_of(schema['allOf'], depth) if schema.key?('allOf')+ return schema unless schema.key?('$ref')++ resolve_schema(component(schema['$ref']), depth + 1)+ end++ # The schema with every reference replaced by what it names, all the+ # way down, so it can be handed to a client that has no document to+ # look `$ref`s up in. A reference that leads back to itself stops at+ # an untyped object rather than recursing.+ #+ # @param schema [Object]+ # @return [Object]+ def inline(schema, seen = [])+ case schema+ when Array+ schema.map { |item| inline(item, seen) }+ when Hash+ return inline_reference(schema, seen) if schema.key?('$ref')+ return inline(merge_all_of(schema['allOf'], 0), seen) if schema.key?('allOf')++ schema.transform_values { |value| inline(value, seen) }+ else+ schema+ end+ end++ # A parameter, followed through a `$ref` to `components/parameters`.+ #+ # @param parameter [Hash]+ # @return [Hash, nil]+ def resolve_parameter(parameter)+ return parameter unless parameter.is_a?(Hash) && parameter.key?('$ref')++ document.dig('components', 'parameters', parameter['$ref'].to_s.split('/').last)+ end++ private++ def signature+ ([core_path] + extension_paths.values).map { |path| [path.to_s, (File.mtime(path) if File.exist?(path))] }+ end++ def inline_reference(schema, seen)+ reference = schema['$ref']+ return { 'type' => 'object' } if seen.include?(reference)++ target = component(reference)+ target ? inline(target, seen + [reference]) : { 'type' => 'object' }+ end++ def component(reference)+ name = reference.to_s.split('/').last+ document.dig('components', 'schemas', name)+ end++ def merge_all_of(parts, depth)+ parts.filter_map { |part| resolve_schema(part, depth + 1) }.each_with_object({}) do |part, merged|+ merged['properties'] = (merged['properties'] || {}).merge(part['properties'] || {})+ merged['required'] = (merged['required'] || []) | Array(part['required'])+ end+ end++ def load_document+ @sources = {}+ @conflicts = []+ merged = read(core_path)+ record_sources(merged, 'spree_api')++ extension_paths.each do |engine, path|+ merge!(merged, read(path), engine)+ end++ merged+ end++ # A document that is missing or does not parse is not a boot failure:+ # its operations are simply not offered, which is the safe direction.+ def read(path)+ return {} unless File.exist?(path)++ document = YAML.unsafe_load_file(path)+ return document if valid?(document)++ Rails.logger.warn("[Spree] the admin API document #{path} is not an OpenAPI document; it is ignored")+ {}+ rescue StandardError => e+ Rails.logger.warn("[Spree] could not read the admin API document #{path}: #{e.class}: #{e.message}")+ {}+ end++ # An OpenAPI document whose operations are objects: anything else+ # would raise in a reader that digs into it, on every agent request.+ def valid?(document)+ document.is_a?(Hash) && document.key?('openapi') &&+ Array(document['paths']).all? { |path, item| path.is_a?(String) && valid_path_item?(item) } &&+ (document['components'].nil? || document['components'].is_a?(Hash))+ end++ def valid_path_item?(item)+ item.is_a?(Hash) && item.all? do |key, operation|+ next true unless HTTP_VERBS.include?(key)++ operation.is_a?(Hash) && valid_request_body?(operation['requestBody'])+ end+ end++ # The catalog digs `content`, `application/json` and `schema`, so each+ # is an object where present.+ def valid_request_body?(body)+ return true if body.nil?+ return false unless body.is_a?(Hash)+ return true if body['content'].nil?+ return false unless body['content'].is_a?(Hash)++ json = body['content']['application/json']+ json.nil? || (json.is_a?(Hash) && (json['schema'].nil? || json['schema'].is_a?(Hash)))+ end++ def conflict(message)+ @conflicts << message+ Rails.logger.error("[Spree] admin API documents conflict: #{message}")+ end++ def record_sources(document, engine)+ Array(document['paths']).each do |path, operations|+ operations.each_key { |verb| @sources[[path, verb.to_s]] = engine if HTTP_VERBS.include?(verb.to_s) }+ end+ end++ def merge!(merged, addition, engine)+ merged['paths'] ||= {}+ Array(addition['paths']).each do |path, operations|+ existing = merged['paths'][path] ||= {}+ operations.each do |key, value|+ # Path-level keys (`parameters`) describe the path, not an+ # operation, and two documents for one path share them.+ next existing[key] ||= value unless HTTP_VERBS.include?(key)++ if existing.key?(key)+ conflict("#{key.upcase} #{path} is documented by both #{@sources[[path, key]]} and #{engine}")+ next+ end++ existing[key] = value+ @sources[[path, key]] = engine+ end+ end++ components = merged['components'] ||= {}+ Array(addition['components']).each do |section, definitions|+ next unless definitions.is_a?(Hash)++ existing = components[section] ||= {}+ definitions.each do |name, definition|+ if existing.key?(name) && existing[name] != definition+ conflict("the #{name} #{section.singularize} is defined differently by #{engine} and an earlier document")+ next+ end++ existing[name] = definition+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/lib/spree/api/agent_operations.rb b/spree/api/lib/spree/api/agent_operations.rbnew file mode 100644index 0000000000..fbe27817e0--- /dev/null+++ b/spree/api/lib/spree/api/agent_operations.rb@@ -0,0 +1,300 @@+module Spree+ module Api+ # Fills {Spree::AgentTools::OperationCatalog} from the merged Admin API+ # document ({AdminDocument}) and the routes behind it.+ #+ # Every write operation that is not a resource's plain create, update or+ # destroy becomes a tool — cancel, capture, approve, send — unless its+ # spec opts it out with a reason. CRUD stays with the generic tools, and a+ # read becomes a tool only when its spec opts it in. Nothing here is a+ # list of tools: an endpoint that gains an rswag spec is a tool in the+ # same commit, core's or an extension's.+ #+ # See docs/plans/6.0-agent-tools-from-openapi.md.+ module AgentOperations+ WRITE_VERBS = %w[post patch put delete].freeze+ CRUD_ACTIONS = %w[index show create update destroy].freeze+ ADMIN_PREFIX = '/api/v3/admin/'.freeze++ # The opt-out and opt-in marks an rswag spec sets (see the `agent_tool`+ # spec helper), and the reason an opt-out must carry.+ AGENT_KEY = 'x-spree-agent'.freeze+ REASON_KEY = 'x-spree-agent-reason'.freeze++ # The line `admin_scope` appends to a description. It is for the+ # rendered docs; a tool is already offered only to a key holding it.+ SCOPE_NOTE = /^\*\*Required scope:\*\*.*$/++ class << self+ # Registers this walk as how the catalog fills itself, and marks it+ # stale so the next reader gets a fresh one.+ #+ # @return [void]+ def stale!+ Spree::AgentTools::OperationCatalog.deriver = -> { install }+ Spree::AgentTools::OperationCatalog.stale!+ Spree::AgentTools::OperationTool.clear_cache!+ AdminDocument.refresh!+ AgentWriteSchemas.reset!+ end++ # @param catalog [Module] defaults to the core catalog+ # @return [Integer] how many operations were registered+ def install(catalog: Spree::AgentTools::OperationCatalog)+ catalog.reset!+ @models = {}++ by_route = candidates.index_by { |candidate| [candidate[:verb], candidate[:path]] }+ included = by_route.values.select { |candidate| disposition(candidate) == :included }+ listed = resolve_collisions(included.filter_map { |candidate| safe_entry_for(candidate) })+ listed.each { |entry| catalog.register(**entry) }+ register_aliases(catalog, by_route, listed.to_set { |entry| entry[:name] })++ listed.size+ end++ # Every admin operation in the document, with the route and+ # controller it resolves to. Public for the contract spec, which+ # reports the operations that resolve to nothing.+ #+ # @return [Array<Hash>]+ def candidates+ routes = route_index++ Array(AdminDocument.document['paths']).flat_map do |path, operations|+ next [] unless path.is_a?(String) && path.start_with?(ADMIN_PREFIX) && operations.is_a?(Hash)++ operations.filter_map do |verb, operation|+ next unless operation.is_a?(Hash) && (WRITE_VERBS + ['get']).include?(verb)++ { path: path, verb: verb, operation: operation, route: routes[[verb, path]],+ path_parameters: Array(operations['parameters']) }+ end+ end+ end++ # Whether an operation becomes a listed tool, and if not, why.+ #+ # @param candidate [Hash]+ # @return [Symbol] :included, :crud, :read, :opted_out, :unrouted,+ # :unscoped or :withheld+ def disposition(candidate)+ return :unrouted if candidate[:route].nil?++ controller = candidate[:route][:controller]+ return :unscoped if controller.nil? || scope_of(controller).blank?+ return :withheld if withheld?(controller)++ flag = candidate[:operation][AGENT_KEY]+ return :opted_out if flag == false++ if candidate[:verb] == 'get'+ flag == true ? :included : :read+ elsif CRUD_ACTIONS.include?(candidate[:route][:action])+ # A create that is really an action — receiving stock against a+ # transfer — names its tool explicitly, and is then offered as one.+ candidate[:operation]['operationId'].present? ? :included : :crud+ else+ :included+ end+ end++ # Every admin route, with its path in OpenAPI form, from the engine's+ # routes — where an extension's admin routes are drawn too. Public for+ # the contract spec, which checks each against the document.+ #+ # @return [Array<Hash>] `{verb:, path:, controller:, action:}`+ def admin_routes+ Spree::Core::Engine.routes.routes.flat_map do |route|+ controller_path = route.defaults[:controller].to_s+ next [] unless controller_path.start_with?('spree/api/v3/admin')++ path = route.path.spec.to_s.sub('(.:format)', '').gsub(/:([a-z_]+)/, '{\1}')+ route.verb.to_s.split('|').map do |verb|+ { verb: verb.downcase, path: path, controller: controller_class(controller_path),+ action: route.defaults[:action].to_s }+ end+ end+ end++ # The tool name an operation gets: its `operationId`, or the resource+ # and the action.+ #+ # @return [String]+ def tool_name(candidate)+ candidate[:operation]['operationId'].presence ||+ "#{resource_key(candidate[:route][:controller])}_#{candidate[:route][:action]}"+ end++ private++ # One operation the catalog cannot read is left out and logged, rather+ # than taking every other tool down with it: validating a document's+ # shape up front cannot foresee every way a generated file goes wrong.+ def safe_entry_for(candidate)+ entry_for(candidate)+ rescue StandardError => e+ Rails.logger.error("[Spree] agent tool for #{candidate[:verb].upcase} #{candidate[:path]} left out: " \+ "#{e.class}: #{e.message}")+ nil+ end++ def entry_for(candidate)+ operation = candidate[:operation]+ controller = candidate[:route][:controller]+ name = tool_name(candidate)+ read = candidate[:verb] == 'get'+ # A read takes its arguments as query parameters, a write as its body.+ body = read ? query_schema(Array(candidate[:path_parameters]) + Array(operation['parameters'])) : request_body(operation)++ {+ name: name,+ verb: candidate[:verb],+ path: candidate[:path],+ summary: operation['summary'].to_s,+ description: description_for(operation),+ permission: "#{scope_kind(controller, candidate[:route][:action])}_#{scope_of(controller)}",+ resource_key: resource_key(controller),+ path_params: candidate[:path].scan(/\{([a-z_]+)\}/).flatten,+ path_descriptions: path_descriptions(candidate[:path_parameters] + Array(operation['parameters'])),+ body_properties: body.fetch('properties', {}),+ body_required: Array(body['required']),+ legacy_parameters: Spree::AgentTools::LegacyTools.parameters_for(name, candidate[:verb], candidate[:path])+ }+ end++ # A 6.0.0 tool whose name is no longer derived — it pointed at a+ # create, or carried its workflow's name — stays callable through+ # 6.0.x, unlisted, under that name.+ def register_aliases(catalog, by_route, listed_names)+ # The catalog is still being filled, so the names already offered+ # are passed in rather than read back from it.+ Spree::AgentTools::LegacyTools::TOOLS.each do |old, tool|+ next if listed_names.include?(old)++ candidate = by_route[[tool[:verb], tool[:path]]]+ next unless candidate && %i[included crud].include?(disposition(candidate))++ entry = safe_entry_for(candidate)+ catalog.register_alias(**entry, name: old, legacy_parameters: tool[:parameters]) if entry+ end+ end++ # Two operations deriving one name: the shallower path keeps it, and+ # the contract spec fails so the other gets an `operationId`.+ def resolve_collisions(entries)+ entries.group_by { |entry| entry[:name] }.map do |name, claimants|+ next claimants.first if claimants.one?++ kept = claimants.min_by { |entry| [entry[:path].count('{'), entry[:path].length] }+ Rails.logger.warn("[Spree] agent tool #{name} is derived by #{claimants.size} operations; " \+ "#{kept[:verb].upcase} #{kept[:path]} keeps it")+ kept+ end+ end++ # The summary, then the description's opening paragraph: what the+ # operation does, in the words its spec already reviews.+ def description_for(operation)+ prose = operation['description'].to_s.gsub(SCOPE_NOTE, '').strip+ paragraph = prose.split(/\n\s*\n/).first.to_s.squish++ [operation['summary'].to_s.strip.delete_suffix('.'), paragraph].compact_blank.join('. ')+ end++ # Path-level parameters first, so an operation's own description of a+ # segment wins.+ def path_descriptions(parameters)+ parameters.map { |parameter| AdminDocument.resolve_parameter(parameter) }.each_with_object({}) do |parameter, result|+ next unless parameter.is_a?(Hash) && parameter['in'] == 'path'++ result[parameter['name']] = parameter['description'] if parameter['description'].present?+ end+ end++ # Path-level parameters first, so an operation's own one of the same+ # name wins.+ def query_schema(parameters)+ parameters = parameters.map { |parameter| AdminDocument.resolve_parameter(parameter) }.+ select { |parameter| parameter.is_a?(Hash) && parameter['in'] == 'query' }.+ reverse.uniq { |parameter| parameter['name'] }.reverse+ properties = parameters.to_h do |parameter|+ [parameter['name'], json_schema(AdminDocument.inline(parameter['schema'] || {}).merge(+ { 'description' => parameter['description'] }.compact+ ))]+ end++ { 'properties' => properties, 'required' => parameters.select { |p| p['required'] }.map { |p| p['name'] } }+ end++ def request_body(operation)+ content = operation['requestBody'].is_a?(Hash) ? operation['requestBody']['content'] : nil+ schema = content.is_a?(Hash) ? content.dig('application/json', 'schema') : nil+ schema ? json_schema(AdminDocument.inline(schema)) : {}+ end++ # OpenAPI 3.0 marks a nullable field with `nullable: true`; JSON+ # Schema, which a client validates arguments against, says it with a+ # type list.+ def json_schema(schema)+ case schema+ when Array then schema.map { |item| json_schema(item) }+ when Hash+ converted = schema.except('nullable').transform_values { |value| json_schema(value) }+ if schema['nullable'] == true && converted['type'].is_a?(String)+ converted['type'] = [converted['type'], 'null']+ end+ converted+ else schema+ end+ end++ # [verb, OpenAPI path] => the action behind it.+ def route_index+ admin_routes.each_with_object({}) do |route, index|+ index[[route[:verb], route[:path]]] ||= route.slice(:controller, :action)+ end+ end++ def controller_class(controller_path)+ "#{controller_path}_controller".camelize.safe_constantize+ end++ def scope_of(controller)+ controller.try(:_scoped_resource)+ end++ # The scope kind the endpoint itself demands for an action — `read`+ # for the controller's read actions, `write` otherwise — so a tool is+ # offered to exactly the keys the endpoint will let through.+ def scope_kind(controller, action)+ instance = controller.allocate+ reads = instance.respond_to?(:read_actions, true) ? instance.send(:read_actions) : %w[index show]+ Array(reads).map(&:to_s).include?(action) ? 'read' : 'write'+ rescue StandardError, NotImplementedError+ 'write'+ end++ # Controllers whose records carry a live credential — the ones the+ # resource map withholds — offer no tools either: an action on an API+ # key or a webhook endpoint answers with the secret.+ def withheld?(controller)+ model = model_for(controller)+ model && AgentResourceMap::WITHHELD_MODELS.include?(model.name)+ end++ # Keyed the way the resource map keys the model, so a tool's+ # resource_key finds its entry there.+ def resource_key(controller)+ model = model_for(controller)+ model ? AgentResourceMap.key_for(model) : controller.controller_name+ end++ # Once per controller per derivation: every operation it serves asks.+ def model_for(controller)+ (@models ||= {}).fetch(controller) { @models[controller] = AgentResourceMap.model_for(controller) }+ end+ end+ end+ end+enddiff --git a/spree/api/lib/spree/api/agent_resource_map.rb b/spree/api/lib/spree/api/agent_resource_map.rbindex 4d98add259..aa7ca11baa 100644--- a/spree/api/lib/spree/api/agent_resource_map.rb+++ b/spree/api/lib/spree/api/agent_resource_map.rb@@ -199,6 +199,24 @@ module Spree}end+ # The plural the resource is addressed by, taken from the model so two+ # controllers serving the same model (a nested one and a top-level one)+ # agree on it. The operation catalog keys its tools the same way.+ #+ # @param model [Class]+ # @return [String]+ def key_for(model)+ model.model_name.element.pluralize+ end++ # The model a controller serves, or nil for one that serves none.+ #+ # @param controller [Class]+ # @return [Class, nil]+ def model_for(controller)+ safely(controller.allocate, :model_class)+ end+private# What the controller does with its own collection. A controller that@@ -313,13 +331,6 @@ module Spreefalseend- # The plural the resource is addressed by, taken from the model so two- # controllers serving the same model (a nested one and a top-level one)- # agree on it.- def key_for(model)- model.model_name.element.pluralize- end-# `Spree::Base.for_store` falls back to the bare class for a model with# no Store association, which would hand this store's agent every# store's rows. A model that defines its own `for_store` has made adiff --git a/spree/api/lib/spree/api/agent_workflow_endpoints.rb b/spree/api/lib/spree/api/agent_workflow_endpoints.rbdeleted file mode 100644index 562a28adb6..0000000000--- a/spree/api/lib/spree/api/agent_workflow_endpoints.rb+++ /dev/null@@ -1,113 +0,0 @@-module Spree- module Api- # Which Admin API operation runs each workflow, derived rather than listed.- #- # Walk the admin routes; for each one, read the controller source and ask- # whether the action behind it calls that workflow. The verb and path come- # from the route, and the body keys from the generated OpenAPI document —- # which is the only place that records a rename (a cancellation's- # `reason:` keyword travels as `cancel_reason_id`).- #- # Read off the controllers for the same reason {AgentResourceMap} is: a- # workflow that gains an endpoint is dispatched without anyone editing a- # file, and one whose endpoint goes away stops being dispatched.- module AgentWorkflowEndpoints- # Where a controller declares a workflow for the base class to run,- # rather than calling it inside an action of its own.- DECLARED_IN = { 'create_workflow' => 'create', 'update_workflow' => 'update' }.freeze-- class << self- # @param map [Module]- # @return [Integer] how many workflows were mapped- def install(map: Spree::AgentTools::WorkflowEndpoints)- map.reset!- keys = Spree::AgentTools::DefaultCatalog::WORKFLOWS.keys- document = openapi_document-- admin_routes.each do |route|- source = controller_source(route[:controller])- next if source.nil?-- keys.each do |key|- # `find` would derive, and deriving is what this is — read the- # entries already registered instead.- next if map.registered.key?(key)- next unless action_calling(source, key) == route[:action]-- map.register(key: key, verb: route[:verb], path: route[:path],- body_keys: body_keys_for(document, route))- end- end-- map.registered.size- end-- private-- def admin_routes- Spree::Core::Engine.routes.routes.filter_map do |route|- controller = route.defaults[:controller].to_s- next unless controller.start_with?('spree/api/v3/admin')-- { controller: controller, action: route.defaults[:action].to_s,- verb: route.verb.to_s, path: route.path.spec.to_s.sub('(.:format)', '') }- end- end-- # Which action calls this workflow: the `def` nearest above the call.- # A declaration consumed by the base class names the action it serves- # instead.- def action_calling(source, key)- index = source.index("Spree.#{key}")- return if index.nil?-- enclosing = source[0...index].scan(/^\s+def ([a-z_]+)/).flatten.last- DECLARED_IN.fetch(enclosing, enclosing)- end-- def controller_source(controller_path)- @sources ||= {}- return @sources[controller_path] if @sources.key?(controller_path)-- @sources[controller_path] = begin- klass = "#{controller_path.camelize}Controller".safe_constantize- file = klass && Object.const_source_location(klass.name)&.first- file && File.exist?(file) ? File.read(file) : nil- rescue StandardError- nil- end- end-- # What the operation's request body accepts, in the names the wire- # uses. A workflow keyword and its body key often differ, and the- # document is where that difference is recorded.- def body_keys_for(document, route)- operation = document.dig('paths', openapi_path(route[:path]), route[:verb].downcase)- schema = operation&.dig('requestBody', 'content', 'application/json', 'schema')- # Bodies are declared once and published as components, so the- # operation points at one rather than carrying its properties.- schema = Spree::Api::AgentWriteSchemas.resolve_schema(schema)-- (schema&.dig('properties') || {}).keys- end-- def openapi_path(path)- path.gsub(/:([a-z_]+)/) { "{#{Regexp.last_match(1)}}" }- end-- # A body the document does not describe is simply passed through- # unchecked.- #- # `AgentWriteSchemas` already holds this file parsed, so it is read- # through there rather than a second time: the document is nearly a- # megabyte, and parsing it twice at boot is a second of nothing.- def openapi_document- Spree::Api::AgentWriteSchemas.document- rescue StandardError => e- Rails.logger.warn("[Spree] could not read the admin API document: #{e.class}: #{e.message}")- {}- end- end- end- end-enddiff --git a/spree/api/lib/spree/api/agent_write_schemas.rb b/spree/api/lib/spree/api/agent_write_schemas.rbindex 47097648f7..91e44bb562 100644--- a/spree/api/lib/spree/api/agent_write_schemas.rb+++ b/spree/api/lib/spree/api/agent_write_schemas.rb@@ -11,8 +11,8 @@ module Spree# fill a form in correctly. Reading it means the generic write tools offer# exactly the documented endpoint and nothing else.#- # Loaded once, lazily: the document is well over a megabyte, and an- # installation with no agent client should never pay for parsing it.+ # Read from {AdminDocument}, so an extension's documented resources+ # count the same as core's.module AgentWriteSchemas# A collection endpoint under the admin namespace: `/api/v3/admin/markets`# but not `/api/v3/admin/markets/{id}` or a nested child.@@ -33,29 +33,25 @@ module Spreeself.for(key).keysend- # Where the generated document lives: `docs/` in a source checkout,- # or the copy the release packs into the gem. Resolved lazily: the- # engine class does not exist yet while this file loads.+ # Core's generated document, which the merged one starts from.## @return [Pathname]def spec_path- source = Spree::Api::Engine.root.join('..', '..', 'docs', 'api-reference', 'admin.yaml')- source.exist? ? source : Spree::Api::Engine.root.join('openapi', 'admin.yaml')+ AdminDocument.core_pathend- # The parsed document, for a reader that needs more of it than the- # write bodies — the workflow endpoint map wants the member actions'- # bodies too, and parsing a megabyte of YAML twice is wasteful.+ # The merged document — core's and every extension's — so an+ # extension's resources are generically writable the same way core's+ # are.## @return [Hash]def document- @document ||= begin- path = spec_path- File.exist?(path) ? (YAML.unsafe_load_file(path) || {}) : {}- rescue StandardError => e- Rails.logger.warn("[Spree] could not read the admin API document: #{e.class}: #{e.message}")- {}- end+ AdminDocument.document+ end++ # @return [void]+ def reset!+ @schemas = nilendprivate@@ -64,17 +60,8 @@ module Spree@schemas ||= load_schemasend- # A missing or unparseable document is not a boot failure: the generic- # write tools simply offer nothing, which is the safe direction.def load_schemas- path = spec_path- return {} unless File.exist?(path)-- document = YAML.unsafe_load_file(path)extract(document)- rescue StandardError => e- Rails.logger.warn("[Spree] could not read admin API write schemas: #{e.class}: #{e.message}")- {}enddef extract(document)@@ -98,32 +85,9 @@ module Spreepublic- # A request body is declared once per endpoint and published as a- # component, so the operation carries a `$ref` to it rather than the- # properties themselves. A body that builds on a shared shape is an- # `allOf` of that shape and its own fields, read as one object.- # Followed a few hops, which is as deep as the generated document- # nests them.- #- # @param schema [Hash, nil] a schema that may be a reference- # @return [Hash, nil] the schema it names+ # @see AdminDocument.resolve_schemadef resolve_schema(schema, depth = 0)- return unless schema.is_a?(Hash)- return if depth > 3- return merge_all_of(schema['allOf'], depth) if schema.key?('allOf')- return schema unless schema.key?('$ref')-- name = schema['$ref'].to_s.split('/').last- resolve_schema(document.dig('components', 'schemas', name), depth + 1)- end-- private-- def merge_all_of(parts, depth)- parts.filter_map { |part| resolve_schema(part, depth + 1) }.each_with_object({}) do |part, merged|- merged['properties'] = (merged['properties'] || {}).merge(part['properties'] || {})- merged['required'] = (merged['required'] || []) | Array(part['required'])- end+ AdminDocument.resolve_schema(schema, depth)endendenddiff --git a/spree/api/lib/spree/api/engine.rb b/spree/api/lib/spree/api/engine.rbindex c428828e45..a932e00db5 100644--- a/spree/api/lib/spree/api/engine.rb+++ b/spree/api/lib/spree/api/engine.rb@@ -2,10 +2,11 @@ require 'rails/engine'require_relative 'dependencies'require_relative 'configuration'+require_relative 'admin_document'require_relative 'agent_write_schemas'require_relative 'agent_resource_map'require_relative 'agent_membership_map'-require_relative 'agent_workflow_endpoints'+require_relative 'agent_operations'require_relative 'oauth'module Spree@@ -63,6 +64,7 @@ module Spree# not they run an agent client. The first caller pays instead.config.to_prepare doSpree::Api::AgentResourceMap.stale!+ Spree::Api::AgentOperations.stale!end# Add API event subscribersdiff --git a/spree/api/lib/spree/api/testing_support/agent_tools.rb b/spree/api/lib/spree/api/testing_support/agent_tools.rbnew file mode 100644index 0000000000..eec4de16a7--- /dev/null+++ b/spree/api/lib/spree/api/testing_support/agent_tools.rb@@ -0,0 +1,35 @@+module Spree+ module Api+ module TestingSupport+ # rswag helpers for what an admin operation means to agents. Every+ # write action an admin key may call is an agent tool built from its+ # operation; these mark the exceptions in the document itself, where a+ # reviewer sees them next to the endpoint.+ #+ # patch 'Anonymize a customer' do+ # agent_tool false, reason: 'Irreversible erasure under GDPR Art. 17.'+ # end+ #+ # get 'List quote statuses' do+ # agent_tool true # a read becomes a tool only when it opts in+ # end+ #+ # Core and extensions extend their request specs with this module:+ #+ # RSpec.configure { |config| config.extend Spree::Api::TestingSupport::AgentTools, type: :request }+ #+ # See docs/plans/6.0-agent-tools-from-openapi.md.+ module AgentTools+ # @param enabled [Boolean]+ # @param reason [String, nil] required to opt a write out+ # @return [void]+ def agent_tool(enabled = true, reason: nil)+ raise ArgumentError, 'an operation opted out of agent tools needs a reason' if !enabled && reason.blank?++ metadata[:operation][Spree::Api::AgentOperations::AGENT_KEY.to_sym] = enabled+ metadata[:operation][Spree::Api::AgentOperations::REASON_KEY.to_sym] = reason if reason+ end+ end+ end+ end+enddiff --git a/spree/api/lib/spree/api/testing_support/agent_tools_contract.rb b/spree/api/lib/spree/api/testing_support/agent_tools_contract.rbnew file mode 100644index 0000000000..2479bf505b--- /dev/null+++ b/spree/api/lib/spree/api/testing_support/agent_tools_contract.rb@@ -0,0 +1,110 @@+require 'spree/api/testing_support/agent_tools'++# The contract between an engine's admin endpoints and the agent tools built+# from them. Core includes it, and so does every extension that adds admin+# endpoints:+#+# require 'spree/api/testing_support/agent_tools_contract'+#+# RSpec.describe 'agent tools' do+# it_behaves_like 'an engine whose admin writes are agent tools', MyExtension::Engine+# end+#+# An admin write cannot land without an operation describing it, an opt-out+# without its reason, or two operations claiming one tool name.+#+# See docs/plans/6.0-agent-tools-from-openapi.md.+RSpec.shared_examples 'an engine whose admin writes are agent tools' do |engine|+ operations = Spree::Api::AgentOperations+ root = engine.root.to_s+ defined_here = lambda do |controller|+ controller && Object.const_source_location(controller.name)&.first&.start_with?(root)+ end++ # The admin operations this engine's own controllers serve.+ let(:engine_candidates) do+ operations.candidates.select { |candidate| defined_here.call(candidate.dig(:route, :controller)) }+ end++ let(:engine_routes) do+ operations.admin_routes.filter_map do |route|+ next unless operations::WRITE_VERBS.include?(route[:verb]) && !operations::CRUD_ACTIONS.include?(route[:action])++ [route[:verb], route[:path]] if defined_here.call(route[:controller])+ end.uniq+ end++ # The tool name each listed action derives, before collisions are settled.+ let(:included_names) do+ engine_candidates.select { |candidate| operations.disposition(candidate) == :included }.+ map { |candidate| operations.tool_name(candidate) }+ end++ it 'documents every admin action its controllers serve' do+ paths = Spree::Api::AdminDocument.document['paths'] || {}+ undocumented = engine_routes.reject { |verb, path| paths.dig(path, verb) }.+ map { |verb, path| "#{verb.upcase} #{path}" }++ expect(undocumented).to be_empty, <<~MESSAGE+ These admin actions have no operation in the engine's OpenAPI document, so no+ agent tool and no API reference describes them:++ #{undocumented.join("\n ")}++ Write an rswag integration spec for each, then regenerate the document.+ MESSAGE+ end++ it 'gives every opt-out a reason' do+ unexplained = engine_candidates.filter_map do |candidate|+ operation = candidate[:operation]+ next unless operation[operations::AGENT_KEY] == false && operation[operations::REASON_KEY].blank?++ "#{candidate[:verb].upcase} #{candidate[:path]}"+ end++ expect(unexplained).to be_empty+ end++ # Across every engine, not only this one: an extension's action deriving+ # a core name would otherwise lose to the shallower path, quietly.+ it 'derives a distinct tool name for every action' do+ every_name = operations.candidates.select { |candidate| operations.disposition(candidate) == :included }.+ map { |candidate| operations.tool_name(candidate) }+ duplicated = every_name.tally.select { |name, count| count > 1 && included_names.include?(name) }.keys++ expect(duplicated).to be_empty, "Give these operations an operationId: #{duplicated.join(', ')}"+ end++ # A hand-registered tool keeps its name, so an operation deriving the same+ # one would vanish from every agent surface.+ it 'claims no name a hand-written tool already has' do+ hand_written = Spree.admin_agent_tools.send(:registered_classes).map(&:tool_name)++ expect(included_names & hand_written).to be_empty+ end++ it 'merges its document into core\'s without a conflict' do+ expect(Spree::Api::AdminDocument.conflicts).to be_empty+ end++ it 'names every tool the way MCP accepts' do+ catalog = Spree::AgentTools::OperationCatalog+ invalid = (catalog.all + catalog.aliases).map(&:name).+ reject { |name| name.match?(/\A[a-zA-Z0-9_-]{1,64}\z/) }++ expect(invalid).to be_empty+ end++ it 'gives every tool a summary and a permission the catalog knows' do+ faults = included_names.filter_map do |name|+ entry = Spree::AgentTools::OperationCatalog.find(name)+ next "#{name}: not registered" if entry.nil?+ next "#{name}: no summary" if entry.summary.blank?++ "#{name}: unknown permission #{entry.permission}" unless Spree.permissions.key?(entry.permission)+ end++ expect(faults).to be_empty+ end+enddiff --git a/spree/api/lib/spree/api/testing_support/openapi.rb b/spree/api/lib/spree/api/testing_support/openapi.rbindex a3b77bb551..2196dc2a68 100644--- a/spree/api/lib/spree/api/testing_support/openapi.rb+++ b/spree/api/lib/spree/api/testing_support/openapi.rb@@ -1,4 +1,5 @@require 'spree/api/testing_support/v3/base'+require 'spree/api/testing_support/agent_tools'require 'spree/api/testing_support/deterministic_openapi'module Spree@@ -155,7 +156,7 @@ module Spree# and in its Rakefile, `require 'spree/api/testing_support/openapi_tasks'`# for `rake spree:openapi:generate`.module Openapi- HELPERS = [RequestBody, AdminScope, AdminOperation].freeze+ HELPERS = [RequestBody, AdminScope, AdminOperation, AgentTools].freezeclass << self# @param config [RSpec::Core::Configuration]diff --git a/spree/api/lib/spree/api/testing_support/openapi_tasks.rb b/spree/api/lib/spree/api/testing_support/openapi_tasks.rbindex d4d5505e15..7f360f1646 100644--- a/spree/api/lib/spree/api/testing_support/openapi_tasks.rb+++ b/spree/api/lib/spree/api/testing_support/openapi_tasks.rb@@ -1,17 +1,20 @@-# `rake spree:openapi:generate` for an extension: runs its integration specs-# through rswag and writes the `openapi/admin.yaml` its gem ships. Under-# OPENAPI=true the run is reproducible (see deterministic_openapi.rb), so a-# diff in the file means the API changed.+# `rake spree:openapi:generate` for an extension or a Spree application: runs+# its integration specs through rswag and writes the `openapi/admin.yaml` it+# ships. Under OPENAPI=true the run is reproducible (see+# deterministic_openapi.rb), so a diff in the file means the API changed.## RSpec is started only when the task runs, so a Rakefile that loads this-# keeps working in a bundle without rspec-core.-namespace :spree do- namespace :openapi do- desc "Generate openapi/admin.yaml from this extension's integration specs"- task :generate do- pattern = ENV.fetch('PATTERN', 'spec/integration/**/*_spec.rb')- ENV['OPENAPI'] = 'true'- ruby '-S', 'rspec', '--pattern', pattern, '--format', 'Rswag::Specs::SwaggerFormatter', '--order', 'defined'+# keeps working in a bundle without rspec-core. Defined once, however many+# times it is loaded: a second definition would run the specs twice.+unless Rake::Task.task_defined?('spree:openapi:generate')+ namespace :spree do+ namespace :openapi do+ desc 'Generate openapi/admin.yaml from the integration specs here'+ task :generate do+ pattern = ENV.fetch('PATTERN', 'spec/integration/**/*_spec.rb')+ ENV['OPENAPI'] = 'true'+ ruby '-S', 'rspec', '--pattern', pattern, '--format', 'Rswag::Specs::SwaggerFormatter', '--order', 'defined'+ endendendenddiff --git a/spree/api/lib/tasks/openapi.rake b/spree/api/lib/tasks/openapi.rakenew file mode 100644index 0000000000..eb01fb26d8--- /dev/null+++ b/spree/api/lib/tasks/openapi.rake@@ -0,0 +1,5 @@+# `spree task openapi:generate` (`bin/rails spree:openapi:generate`) in a Spree+# application: writes openapi/admin.yaml from the app's own rswag specs, so the+# admin endpoints it adds are documented, and each documented action is an+# agent tool. Extensions get the same task from extension_rake.+load File.expand_path('../spree/api/testing_support/openapi_tasks.rb', __dir__)diff --git a/spree/api/spec/integration/spree/api/v3/admin/categories_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/categories_spec.rbindex 9787b900b3..b50d662e3f 100644--- a/spree/api/spec/integration/spree/api/v3/admin/categories_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/categories_spec.rb@@ -289,6 +289,7 @@ RSpec.describe 'Admin Categories API', type: :request, swagger_doc: 'api-referenpath '/api/v3/admin/categories/{category_id}/products/{id}/reposition' dopatch 'Reposition a category product' dotags 'Categories'+ operationId 'categories_reposition_product'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]diff --git a/spree/api/spec/integration/spree/api/v3/admin/collections_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/collections_spec.rbindex e483354e83..65951de709 100644--- a/spree/api/spec/integration/spree/api/v3/admin/collections_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/collections_spec.rb@@ -268,6 +268,7 @@ RSpec.describe 'Admin Collections API', type: :request, swagger_doc: 'api-referepath '/api/v3/admin/collections/{collection_id}/products/{id}/reposition' dopatch 'Reposition a collection product' dotags 'Collections'+ operationId 'collections_reposition_product'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]diff --git a/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rbindex 1055d33634..2f49e9a26f 100644--- a/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb@@ -88,6 +88,7 @@ RSpec.describe 'Admin Company Tax Identifiers API', type: :request, swagger_doc:post 'Re-check a company tax registration' dotags 'Companies'+ operationId 'company_tax_identifiers_validate'produces 'application/json'security [api_key: [], bearer_auth: []]description <<~DESCdiff --git a/spree/api/spec/integration/spree/api/v3/admin/customer_privacy_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/customer_privacy_spec.rbindex 1d7c82eaa5..6c19aff564 100644--- a/spree/api/spec/integration/spree/api/v3/admin/customer_privacy_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/customer_privacy_spec.rb@@ -59,6 +59,7 @@ RSpec.describe 'Admin Customer Privacy API', type: :request, swagger_doc: 'api-rpath '/api/v3/admin/customers/{id}/anonymize' dopost 'Erase a customer\'s personal data' dotags 'Customers'+ agent_tool false, reason: "Irreversible erasure of a person's data under GDPR Art. 17, which is not something to offer a model behind one confirmation prompt."produces 'application/json'security [api_key: [], bearer_auth: []]description <<~DESCdiff --git a/spree/api/spec/integration/spree/api/v3/admin/customers/tax_identifiers_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/customers/tax_identifiers_spec.rbindex 90d70665f9..741ed52bbb 100644--- a/spree/api/spec/integration/spree/api/v3/admin/customers/tax_identifiers_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/customers/tax_identifiers_spec.rb@@ -86,6 +86,7 @@ RSpec.describe 'Admin Customer Tax Identifiers API', type: :request, swagger_docpost 'Re-check a customer tax registration' dotags 'Customers'admin_sdk_example 'customer-tax-identifiers/validate'+ operationId 'customer_tax_identifiers_validate'produces 'application/json'security [api_key: [], bearer_auth: []]description <<~DESCdiff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/labels_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/labels_spec.rbindex ad2dd6da60..8bf2e215be 100644--- a/spree/api/spec/integration/spree/api/v3/admin/orders/labels_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/labels_spec.rb@@ -50,6 +50,7 @@ RSpec.describe 'Admin Shipping Labels API', type: :request, swagger_doc: 'api-repost 'Buy or record a shipping label' dotags 'Shipping Labels'+ operationId 'shipping_labels_purchase'consumes 'application/json'produces 'application/json'security [{ api_key: [], bearer_auth: [] }]diff --git a/spree/api/spec/integration/spree/api/v3/admin/prices_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/prices_spec.rbindex 1f576a7c07..31832030f9 100644--- a/spree/api/spec/integration/spree/api/v3/admin/prices_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/prices_spec.rb@@ -251,6 +251,7 @@ RSpec.describe 'Admin Prices API', type: :request, swagger_doc: 'api-reference/apath '/api/v3/admin/prices/bulk_destroy' dodelete 'Bulk-delete prices' dotags 'Pricing'+ agent_tool false, reason: 'Deletes many prices in one call behind a single confirmation; delete_resource removes them one at a time.'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]diff --git a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rbindex f105f6cf63..c066e2ef03 100644--- a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb@@ -263,6 +263,8 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-referencepath '/api/v3/admin/products/bulk_status_update' dopost 'Bulk-update product status' dotags 'Products'+ agent_tool false, reason: 'Writes the status column for many products at once, skipping the status workflows ' \+ 'and their events; products_activate, products_archive and products_draft run them.'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]@@ -594,6 +596,7 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-referencepath '/api/v3/admin/products/bulk_destroy' dodelete 'Bulk-delete products' dotags 'Products'+ agent_tool false, reason: 'Deletes many products in one call behind a single confirmation; delete_resource removes them one at a time.'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]diff --git a/spree/api/spec/integration/spree/api/v3/admin/purchase_orders_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/purchase_orders_spec.rbindex cc72d6f90d..90f21ce0d3 100644--- a/spree/api/spec/integration/spree/api/v3/admin/purchase_orders_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/purchase_orders_spec.rb@@ -292,6 +292,7 @@ RSpec.describe 'Admin Purchase Orders API', type: :request, swagger_doc: 'api-repost 'Book in a delivery' dotags 'Purchase Orders'+ operationId 'purchase_orders_receive'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]diff --git a/spree/api/spec/integration/spree/api/v3/admin/reporting_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/reporting_spec.rbindex 3791b9ac21..d7d1b7768b 100644--- a/spree/api/spec/integration/spree/api/v3/admin/reporting_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/reporting_spec.rb@@ -10,6 +10,7 @@ RSpec.describe 'Admin Reporting API', type: :request, swagger_doc: 'api-referencpath '/api/v3/admin/reporting/query' dopost 'Run a reporting query' dotags 'Reports'+ agent_tool false, reason: 'query_report runs this query, with describe_reporting to learn the vocabulary first.'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]diff --git a/spree/api/spec/integration/spree/api/v3/admin/returns_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/returns_spec.rbindex ab6f72a430..466f5ba98b 100644--- a/spree/api/spec/integration/spree/api/v3/admin/returns_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/returns_spec.rb@@ -304,6 +304,7 @@ RSpec.describe 'Admin Returns API', type: :request, swagger_doc: 'api-reference/patch 'Refund a return label' dotags 'Orders'admin_sdk_example 'order-returns/labels-refund'+ operationId 'return_labels_refund'produces 'application/json'security [api_key: [], bearer_auth: []]description 'Asks the carrier to refund a purchased return label the customer never used, such as when the return is canceled. An uploaded label has nothing to refund.'diff --git a/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rbindex fd1eea3b7a..b1a19600b6 100644--- a/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb@@ -862,6 +862,7 @@ RSpec.describe 'Admin Sellers API', type: :request, swagger_doc: 'api-reference/patch 'Mark a payout paid' dotags 'Sellers'+ agent_tool false, reason: 'Settles a payout against the payment provider, reconciling against provider state an agent cannot see.'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]diff --git a/spree/api/spec/integration/spree/api/v3/admin/stock_levels_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/stock_levels_spec.rbindex bc4b5f08c8..40ee2d8128 100644--- a/spree/api/spec/integration/spree/api/v3/admin/stock_levels_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/stock_levels_spec.rb@@ -59,6 +59,7 @@ RSpec.describe 'Admin Stock Levels API', type: :request, swagger_doc: 'api-referpath '/api/v3/admin/stock_levels/bulk_upsert' dopost 'Bulk-upsert stock levels' dotags 'Stock'+ agent_tool false, reason: 'set_stock calls this endpoint already, taking stock by SKU and location the way a merchant names them.'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]diff --git a/spree/api/spec/integration/spree/api/v3/admin/stock_transfers_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/stock_transfers_spec.rbindex 8cb347841a..7526228516 100644--- a/spree/api/spec/integration/spree/api/v3/admin/stock_transfers_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/stock_transfers_spec.rb@@ -354,6 +354,7 @@ RSpec.describe 'Admin Stock Transfers API', type: :request, swagger_doc: 'api-repost 'Count a delivery in' dotags 'Stock Transfers'+ operationId 'stock_transfers_receive'consumes 'application/json'produces 'application/json'security [api_key: [], bearer_auth: []]diff --git a/spree/api/spec/lib/spree/api/admin_document_spec.rb b/spree/api/spec/lib/spree/api/admin_document_spec.rbnew file mode 100644index 0000000000..49912d7dc6--- /dev/null+++ b/spree/api/spec/lib/spree/api/admin_document_spec.rb@@ -0,0 +1,82 @@+require 'spec_helper'++# Core's admin document merged with the one each extension ships. See+# docs/plans/6.0-agent-tools-from-openapi.md.+RSpec.describe Spree::Api::AdminDocument do+ let(:dir) { Dir.mktmpdir }+ let(:extension_path) { Pathname.new(dir).join('admin.yaml') }++ before do+ described_class.reset!+ allow(described_class).to receive(:extension_paths).and_return('my_extension' => extension_path)+ end++ after do+ described_class.reset!+ FileUtils.remove_entry(dir)+ end++ def write_extension(document)+ File.write(extension_path, { 'openapi' => '3.0.3' }.merge(document).to_yaml)+ end++ it 'adds an extension\'s operations to core\'s' do+ write_extension('paths' => { '/api/v3/admin/quotes/{id}/send' => { 'patch' => { 'summary' => 'Send a quote' } } })++ expect(described_class.document.dig('paths', '/api/v3/admin/quotes/{id}/send', 'patch', 'summary')).to eq('Send a quote')+ expect(described_class.source_of('/api/v3/admin/quotes/{id}/send', 'patch')).to eq('my_extension')+ expect(described_class.document.dig('paths', '/api/v3/admin/orders/{id}/cancel', 'patch')).to be_present+ end++ # A conflict is left out and reported, not raised: one extension's stale+ # document must not take every agent tool down with it.+ it 'keeps core\'s operation when an extension documents the same one' do+ write_extension('paths' => { '/api/v3/admin/orders/{id}/cancel' => { 'patch' => { 'summary' => 'Hijacked' } } })++ expect(described_class.document.dig('paths', '/api/v3/admin/orders/{id}/cancel', 'patch', 'summary')).to eq('Cancel an order')+ expect(described_class.conflicts).to include(a_string_including('PATCH /api/v3/admin/orders/{id}/cancel'))+ end++ it 'does not count a path\'s shared parameters as a conflict' do+ write_extension('paths' => { '/api/v3/admin/orders/{id}/cancel' => { 'parameters' => [{ 'name' => 'id', 'in' => 'path' }] } })++ expect(described_class.conflicts).to be_empty+ end++ it 'ignores a file that is not an OpenAPI document' do+ File.write(extension_path, %w[not a document].to_yaml)++ expect(described_class.document.dig('paths', '/api/v3/admin/orders/{id}/cancel', 'patch')).to be_present+ end++ it 'ignores a document whose operation is not an object' do+ write_extension('paths' => { '/api/v3/admin/widgets' => { 'patch' => 'broken' } })++ expect(described_class.document.dig('paths', '/api/v3/admin/widgets')).to be_nil+ end++ it 'ignores a document whose request body is not an object' do+ write_extension('paths' => { '/api/v3/admin/widgets' => { 'post' => { 'requestBody' => { 'content' => { 'application/json' => 'broken' } } } } })++ expect(described_class.document.dig('paths', '/api/v3/admin/widgets')).to be_nil+ end++ it 'ignores YAML that is not an OpenAPI document' do+ File.write(extension_path, { 'paths' => { '/api/v3/admin/widgets' => { 'patch' => {} } } }.to_yaml)++ expect(described_class.document.dig('paths', '/api/v3/admin/widgets')).to be_nil+ end++ it 'follows a parameter reference into the extension\'s components' do+ write_extension('components' => { 'parameters' => { 'WidgetId' => { 'name' => 'id', 'in' => 'path' } } })++ expect(described_class.resolve_parameter('$ref' => '#/components/parameters/WidgetId')['in']).to eq('path')+ end++ it 'keeps core\'s component when an extension defines it differently' do+ write_extension('components' => { 'schemas' => { 'Order' => { 'type' => 'string' } } })++ expect(described_class.document.dig('components', 'schemas', 'Order', 'type')).to eq('object')+ expect(described_class.conflicts).to include(a_string_including('Order'))+ end+enddiff --git a/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb b/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rbindex 5597828d7e..f4ae89456e 100644--- a/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb+++ b/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb@@ -1,41 +1,22 @@require 'spec_helper'+require 'spree/api/testing_support/agent_tools_contract'-# The Admin API's controllers are the reference wiring for what an agent may-# do: they define which workflow writes a resource, which permission gates it,-# and how a request becomes workflow keywords. These examples keep the agent-# catalog honest against them, so a new admin endpoint cannot quietly arrive-# without an agent deciding what to do about it.+# The Admin API is the reference wiring for what an agent may do: its+# operations are the action tools, and its controllers define the resources+# the generic tools reach. These examples keep the agent catalog honest+# against them, so a new admin endpoint cannot quietly arrive without an+# agent deciding what to do about it.#-# See docs/plans/6.0-mcp-server.md.+# See docs/plans/6.0-mcp-server.md and docs/plans/6.0-agent-tools-from-openapi.md.RSpec.describe 'agent tool contract' do- # Every `Spree.<key>_workflow` an admin controller calls, found by reading- # the controller sources — the same way a reviewer would.- def workflows_invoked_by_admin_controllers- root = Spree::Api::Engine.root.join('app', 'controllers', 'spree', 'api', 'v3', 'admin')-- Dir.glob(root.join('**', '*.rb')).flat_map do |path|- File.read(path).scan(/Spree\.([a-z_]+_workflow)\b/).flatten- end.uniq.map(&:to_sym).sort- end-- # Whether an unmapped model reaches the store through a parent the map does- # hold, which is how Spree::AgentTools::WorkflowTool resolves it.- def mapped_parent?(model_name, mapped)- model_name.constantize.reflect_on_all_associations(:belongs_to).any? do |association|- !association.polymorphic? && mapped.include?(association.klass.name)- end- rescue StandardError- false- end-# Resource keys whose controller guards against a caller granting authority# it does not hold, which the derivation deliberately makes read-only.def authority_keysSpree::Api::AgentResourceMap.controllers.filter_map do |controller|next unless controller.include?(Spree::Api::V3::Admin::RoleGrantGuard)- model = Spree::Api::AgentResourceMap.send(:safely, controller.allocate, :model_class)- model && model.model_name.element.pluralize+ model = Spree::Api::AgentResourceMap.model_for(controller)+ model && Spree::Api::AgentResourceMap.key_for(model)endend@@ -43,169 +24,19 @@ RSpec.describe 'agent tool contract' do# scopes, which the derivation deliberately makes read-only.def contested_keysby_key = Spree::Api::AgentResourceMap.controllers.each_with_object(Hash.new { |h, k| h[k] = [] }) do |controller, result|- model = Spree::Api::AgentResourceMap.send(:safely, controller.allocate, :model_class)+ model = Spree::Api::AgentResourceMap.model_for(controller)next if model.nil? || controller._scoped_resource.blank?- result[model.model_name.element.pluralize] << controller._scoped_resource+ result[Spree::Api::AgentResourceMap.key_for(model)] << controller._scoped_resourceendby_key.select { |_key, scopes| scopes.uniq.size > 1 }.keysend- let(:catalog) { Spree::AgentTools::DefaultCatalog }-- describe 'the workflow allowlist' do- it 'accounts for every workflow an admin controller invokes' do- invoked = workflows_invoked_by_admin_controllers- accounted = catalog::WORKFLOWS.keys + catalog::EXCLUDED_WORKFLOWS.keys-- unaccounted = invoked - accounted-- expect(unaccounted).to be_empty, <<~MESSAGE- These workflows are called by an admin controller but are neither exposed- as agent tools nor excluded with a reason:-- #{unaccounted.join("\n ")}-- Add each to Spree::AgentTools::DefaultCatalog::WORKFLOWS with the write- permission its controller declares, or to EXCLUDED_WORKFLOWS saying why- an agent must not run it.- MESSAGE- end-- it 'exposes nothing an admin controller does not invoke' do- # A workflow no controller reaches has no reference wiring: nothing says- # how a request becomes its keywords, or which permission gates it.- stray = catalog::WORKFLOWS.keys - workflows_invoked_by_admin_controllers-- expect(stray).to be_empty- end-- it 'gives every exclusion a reason' do- expect(catalog::EXCLUDED_WORKFLOWS.values).to all(be_present)- end-- it 'names a permission the catalog knows for every exposed workflow' do- unknown = catalog::WORKFLOWS.filter_map do |key, options|- permission = options.is_a?(Hash) ? options[:permission] : options- "#{key} => #{permission}" unless Spree.permissions.key?(permission)- end-- expect(unknown).to be_empty- end-- it 'gates every exposed workflow with a write permission' do- reads = catalog::WORKFLOWS.filter_map do |key, options|- permission = options.is_a?(Hash) ? options[:permission] : options- key unless permission.start_with?('write_')- end-- expect(reads).to be_empty- end-- it 'resolves every exposed workflow to a class' do- unresolved = catalog::WORKFLOWS.keys.reject { |key| Spree.public_send(key).is_a?(Class) }-- expect(unresolved).to be_empty- end- end-- describe 'schema derivation' do- it 'derives a schema for every exposed workflow' do- failures = catalog::WORKFLOWS.filter_map do |key, options|- options = { permission: options } unless options.is_a?(Hash)- Spree::AgentTools::WorkflowSchema.new(Spree.public_send(key), except: Array(options[:except])).parameters- nil- rescue StandardError => e- "#{key}: #{e.message}"- end-- expect(failures).to be_empty, <<~MESSAGE- Every parameter of an exposed workflow needs a YARD `@param` with a type,- because the tool's schema is derived from it:-- #{failures.join("\n ")}- MESSAGE- end-- # A prefixed id can only be turned into a record under the caller's store.- # The map answers that directly for a store-scoped model; a model scoped- # through its parent (a certificate through its company) is resolved- # through that parent. A model with neither has no tenancy answer at all,- # and must not be a parameter of an exposed workflow.- it 'can resolve every record parameter within a store' do- Spree::Api::AgentResourceMap.install- mapped = Spree::AgentTools::ResourceMap.all.map(&:model_name)-- unresolvable = catalog::WORKFLOWS.flat_map do |key, options|- options = { permission: options } unless options.is_a?(Hash)- schema = Spree::AgentTools::WorkflowSchema.new(Spree.public_send(key), except: Array(options[:except]))-- schema.parameters.filter_map do |parameter|- model_name = parameter[:model_name]- next if model_name.blank? || mapped.include?(model_name)- next if mapped_parent?(model_name, mapped)-- "#{key}.#{parameter[:name]} => #{model_name}"- end- end-- expect(unresolvable).to be_empty, <<~MESSAGE- A record parameter is filled from a prefixed id, which is only safe when- the record can be narrowed to the caller's store — through the resource- map, or through a parent the map holds. These can be narrowed by neither:-- #{unresolvable.join("\n ")}- MESSAGE- end-- # Asserted against the naming convention rather than against the injected- # list, which would be circular: a parameter is only offered because it is- # not on that list, so comparing the two can never fail. A keyword that- # reads as "who did this" and is still offered is the bug worth catching.- it 'never offers a parameter that names who acted' do- # `<verb>ed_by` is the shape that names a person. A `cancel_by` is a- # date the merchant sets, not an actor, so the participle matters.- actor_shaped = /\A(\w+ed_by|created_by|canceler|approver|reviewer|refunder|requester)\z/-- offered = catalog::WORKFLOWS.flat_map do |key, options|- options = { permission: options } unless options.is_a?(Hash)- schema = Spree::AgentTools::WorkflowSchema.new(Spree.public_send(key), except: Array(options[:except]))-- schema.parameters.filter_map do |parameter|- "#{key}.#{parameter[:name]}" if parameter[:name].to_s.match?(actor_shaped)- end- end-- expect(offered).to be_empty, <<~MESSAGE- These parameters name who performed the action, and the answer is the- authenticated principal — never something a caller may claim:-- #{offered.join("\n ")}-- Declare the association with `acted_by` so it is injected, or add the- keyword to WorkflowSchema::UNCONVERTED_PRINCIPAL_PARAMETERS until it is.- MESSAGE- end-- it 'injects every actor association the acted_by registry knows' do- declared = Spree::ActedBy.models.flat_map(&:acted_by_associations).map(&:to_sym)-- expect(Spree::AgentTools::WorkflowSchema.principal_parameter_names).to include(*declared)- end-- it 'gives every exposed workflow a unique tool name' do- names = catalog::WORKFLOWS.keys.map { |key| Spree::AgentTools::WorkflowTool.tool_name_for(Spree.public_send(key)) }-- expect(names).to match_array(names.uniq)- end-- it 'gives every tool a name the protocol accepts' do- invalid = catalog::WORKFLOWS.keys.map { |key| Spree::AgentTools::WorkflowTool.tool_name_for(Spree.public_send(key)) }.- reject { |name| name.match?(/\A[a-zA-Z0-9_-]{1,64}\z/) }-- expect(invalid).to be_empty- end+ # Every admin action is a tool built from its OpenAPI operation; this is+ # the contract an extension includes for its own engine too.+ describe 'the action tools' do+ it_behaves_like 'an engine whose admin writes are agent tools', Spree::Api::Engineenddescribe 'the derived resource map' do@@ -271,7 +102,7 @@ RSpec.describe 'agent tool contract' do# wins and the resource stays read-only.it 'resolves a resource served under two scopes to the narrower, read-only' doby_model = Spree::Api::AgentResourceMap.controllers.each_with_object(Hash.new { |h, k| h[k] = [] }) do |controller, result|- model = Spree::Api::AgentResourceMap.send(:safely, controller.allocate, :model_class)+ model = Spree::Api::AgentResourceMap.model_for(controller)next if model.nil? || controller._scoped_resource.blank?result[model.name] << "read_#{controller._scoped_resource}"@@ -345,7 +176,7 @@ RSpec.describe 'agent tool contract' doexpect(guarded).not_to be_empty, 'expected the anti-amplification guard to be in use somewhere'writable = guarded.filter_map do |controller|- model = Spree::Api::AgentResourceMap.send(:safely, controller.allocate, :model_class)+ model = Spree::Api::AgentResourceMap.model_for(controller)next if model.nil?entry = Spree::AgentTools::ResourceMap.all.find { |candidate| candidate.model_name == model.name }diff --git a/spree/api/spec/swagger_helper.rb b/spree/api/spec/swagger_helper.rbindex e032beb683..817c80a950 100644--- a/spree/api/spec/swagger_helper.rb+++ b/spree/api/spec/swagger_helper.rb@@ -318,6 +318,7 @@ RSpec.configure do |config|config.openapi_format = :yamlconfig.extend Spree::Api::TestingSupport::AdminOperation, type: :request+ config.extend Spree::Api::TestingSupport::AgentTools, type: :request# Auto-generate examples from actual test responses# This captures real response data and embeds it in the OpenAPI specdiff --git a/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb b/spree/api/spec/tools/spree/agent_tools/generic_write_arguments_spec.rbsimilarity index 53%rename from spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rbrename to spree/api/spec/tools/spree/agent_tools/generic_write_arguments_spec.rbindex 4af4d44afe..a4bc39c48e 100644--- a/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/generic_write_arguments_spec.rb@@ -1,9 +1,9 @@require 'spec_helper'-# A workflow tool's arguments arrive as JSON, so every record it is meant to-# act on comes in as a prefixed id. What the tool does between receiving those-# strings and calling the workflow is the whole of its contract.-RSpec.describe 'agent workflow tool arguments' do+# A generic write's arguments arrive as JSON, so every record it is meant to+# act on comes in as a prefixed id, and every attribute is checked against what+# the endpoint permits before it is sent.+RSpec.describe 'agent generic write arguments' dolet(:store) { @default_store }let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }@@ -83,31 +83,6 @@ RSpec.describe 'agent workflow tool arguments' doendend- # Nothing shipped reaches this, but an extension registering a workflow- # whose key does not name a Spree model would: `can?(:create, nil)` answers- # true, so the authorization check passes for exactly the tool nobody can- # vouch for, and the attribute filter keyed off the same lookup falls open- # with it.- describe 'a workflow naming a resource that does not exist' do- let(:tool_class) do- Spree::AgentTools::WorkflowTool.for(:product_create_workflow, permission: 'write_products')- end-- let(:tool) do- instance = tool_class.new(context)- allow(instance).to receive(:created_model).and_return(nil)- allow(instance).to receive(:subject_model).and_return(nil)- instance- end-- it 'refuses rather than authorizing against nothing' do- result = tool.call(attributes: { 'name' => 'Should not be created' })-- expect(result[:error]).to include('does not exist').or include('not one an agent may write')- expect(Spree::Product.where(name: 'Should not be created')).to be_empty- end- end-describe 'an actor the record cannot hold' dolet(:supplier) { create(:supplier, store: store) }let(:stock_location) { store.stock_locations.first || create(:stock_location, store: store) }@@ -148,78 +123,4 @@ RSpec.describe 'agent workflow tool arguments' doexpect(store.purchase_orders.last.created_by).to eq(admin)endend- # A workflow with an endpoint runs through it: the controller's routing,- # authentication, authorization and serializer, rather than a second copy- # of each beside them.- describe 'running through the endpoint' do- it 'dispatches every workflow that has one' do- in_process = Spree::AgentTools::DefaultCatalog::WORKFLOWS.reject do |key, _options|- Spree::AgentTools::WorkflowEndpoints.find(key)- end-- expect(in_process.keys).to be_empty- end-- it 'fills a parent segment from the record the caller named' do- order = create(:order_with_line_items, store: store)- payment = create(:payment, order: order, amount: 10)-- result = tool('payments_void').call(payment: payment.prefixed_id)-- expect(result[:error]).to be_nil- expect(payment.reload.status).to eq('void')- end-- it 'sends a keyword under the name the endpoint documents' do- order = create(:order_ready_to_ship, store: store)-- result = tool('orders_cancel').call(order: order.prefixed_id, cancel_note: 'Duplicate order')-- expect(result[:error]).to be_nil- expect(order.reload.status).to eq('canceled')- end-- it 'does not reach a record in another store' do- theirs = create(:order_ready_to_ship, store: create(:store, code: "other-#{SecureRandom.hex(4)}"))-- result = tool('orders_cancel').call(order: theirs.prefixed_id)-- expect(result[:error]).to be_present- expect(theirs.reload.status).not_to eq('canceled')- end- # A keyword the endpoint carries under another name has to arrive, or the- # tool reports a change it did not make. Three shapes caught real drops- # while this was written: a record renamed by the action- # (`reason:` -> `cancel_reason_id`), an attributes hash that IS the body,- # and a keyword whose record fills a path segment of a different name.- it 'sends a record the action renamed' do- order = create(:order_ready_to_ship, store: store)- reason = store.order_cancellation_reasons.first || create(:order_cancellation_reason, store: store)-- result = tool('orders_cancel').call(order: order.prefixed_id, reason: reason.prefixed_id)-- expect(result[:error]).to be_nil- expect(order.reload.cancel_reason_id).to eq(reason.id)- end-- it 'merges an attributes hash into the body' do- product = create(:product, store: store)- sku = "SKU-#{SecureRandom.hex(3)}"-- result = tool('variants_create').call(product: product.prefixed_id, attributes: { 'sku' => sku })-- expect(result[:error]).to be_nil- expect(Spree::Variant.where(sku: sku)).to exist- end-- it 'fills a path segment from a keyword of a different name' do- order = create(:order_ready_to_ship, store: store)-- result = tool('shipping_labels_purchase').call(owner: order.fulfillments.first.prefixed_id)-- # The provider refuses in test, which is the endpoint answering — a- # segment left unfilled would have been a 404 instead.- expect(result[:error]).not_to match(/not found/i)- end- endenddiff --git a/spree/api/spec/tools/spree/agent_tools/legacy_tools_spec.rb b/spree/api/spec/tools/spree/agent_tools/legacy_tools_spec.rbnew file mode 100644index 0000000000..b6de403bfe--- /dev/null+++ b/spree/api/spec/tools/spree/agent_tools/legacy_tools_spec.rb@@ -0,0 +1,127 @@+require 'spec_helper'++# The tools Spree 6.0.0 offered keep answering through 6.0.x, by their 6.0.0+# names and with their 6.0.0 arguments. These examples check the whole table+# rather than a sample of it, and run every name that is no longer listed end+# to end. See docs/plans/6.0-agent-tools-from-openapi.md.+RSpec.describe Spree::AgentTools::LegacyTools do+ let(:store) { @default_store }+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }+ let(:catalog) { Spree::AgentTools::OperationCatalog }++ def old_tool(name)+ Spree.admin_agent_tools.find_for(name, context)+ end++ # The 6.0.0 catalog, name => permission, read from the allowlist it was+ # built from. The constant is deprecated; reading it here is the point.+ def permissions_in_6_0_0+ Spree::AgentTools::DefaultCatalog.const_get(:WORKFLOWS).to_h do |key, options|+ permission = options.is_a?(Hash) ? options[:permission] : options+ [Spree.public_send(key).workflow_key.tr('.', '_'), permission]+ end+ end++ describe 'the table' do+ it 'resolves every 6.0.0 name to an operation' do+ unresolved = described_class::TOOLS.keys.reject { |name| catalog.find(name) }++ expect(unresolved).to be_empty+ end++ it 'maps every renamed parameter onto an argument the operation takes' do+ faults = described_class::TOOLS.flat_map do |name, tool|+ entry = catalog.find(name)+ accepted = entry.path_params + entry.body_properties.keys++ tool[:parameters].values.grep(String).reject { |target| accepted.include?(target) }.map { |target| "#{name}: #{target}" }+ end++ expect(faults).to be_empty+ end++ it 'keeps the permission each tool had in 6.0.0' do+ changed = permissions_in_6_0_0.filter_map do |name, permission|+ entry = catalog.find(name)+ next if entry.nil? # deliveries_update_tracking, withdrawn on purpose++ "#{name}: #{permission} -> #{entry.permission}" unless entry.permission == permission+ end++ expect(changed).to be_empty+ end++ it 'accounts for every 6.0.0 tool, withdrawn ones by name' do+ missing = permissions_in_6_0_0.keys - described_class::TOOLS.keys++ expect(missing).to eq(['deliveries_update_tracking'])+ end++ it 'leaves only names with no operation of their own unlisted' do+ expect(catalog.aliases.map(&:name)).to contain_exactly(+ 'fulfillments_create', 'refunds_create', 'seller_requirement_submissions_waive',+ 'variants_create', 'variants_update'+ )+ end+ end++ # Each name no longer listed, called the way a 6.0.0 client called it.+ describe 'a name no longer listed' do+ it 'creates a fulfillment from fulfillments_create' do+ order = create(:order_ready_to_ship, store: store)+ location = order.fulfillments.first.stock_location++ result = old_tool('fulfillments_create').call(order: order.prefixed_id, stock_location: location.prefixed_id,+ tracking: 'INPOST-12345', status: 'shipped')++ expect(result[:error]).to be_nil+ expect(order.reload.fulfillments.map(&:tracking)).to include('INPOST-12345')+ expect(result[:deprecations]).to include('order is deprecated: use order_id.')+ end++ it 'refunds a payment from refunds_create' do+ order = create(:order_ready_to_ship, store: store)+ reason = create(:refund_reason)++ result = old_tool('refunds_create').call(order: order.prefixed_id, payment: order.payments.first.prefixed_id,+ amount: '5.00', reason: reason.prefixed_id)++ expect(result[:error]).to be_nil+ expect(Spree::Refund.where(refund_reason_id: reason.id, amount: 5)).to exist+ end++ it 'waives a requirement from seller_requirement_submissions_waive' do+ seller = create(:seller, store: store)+ requirement = create(:attestation_requirement, store: store)++ result = old_tool('seller_requirement_submissions_waive').call(seller: seller.prefixed_id,+ requirement: requirement.prefixed_id)++ expect(result[:error]).to be_nil+ expect(Spree::SellerRequirementSubmission.find_by(seller: seller, requirement: requirement)).to be_waived+ end++ it 'creates a variant from variants_create' do+ product = create(:product, store: store)+ sku = "SKU-#{SecureRandom.hex(3)}"++ result = old_tool('variants_create').call(product: product.prefixed_id, attributes: { 'sku' => sku })++ expect(result[:error]).to be_nil+ expect(product.variants.where(sku: sku)).to exist+ end++ # Named by the variant alone, as 6.0.0 took it: the product it lives+ # under is read off the variant.+ it 'updates a variant from variants_update' do+ variant = create(:variant, product: create(:product, store: store))+ sku = "SKU-#{SecureRandom.hex(3)}"++ result = old_tool('variants_update').call(variant: variant.prefixed_id, attributes: { 'sku' => sku })++ expect(result[:error]).to be_nil+ expect(variant.reload.sku).to eq(sku)+ end+ end+enddiff --git a/spree/api/spec/tools/spree/agent_tools/operation_tool_spec.rb b/spree/api/spec/tools/spree/agent_tools/operation_tool_spec.rbnew file mode 100644index 0000000000..e1e108ddf2--- /dev/null+++ b/spree/api/spec/tools/spree/agent_tools/operation_tool_spec.rb@@ -0,0 +1,260 @@+require 'spec_helper'++# An action tool is an Admin API operation: its name, prose and arguments come+# from the OpenAPI document, and a call is a request to the endpoint. See+# docs/plans/6.0-agent-tools-from-openapi.md.+RSpec.describe Spree::AgentTools::OperationTool do+ let(:store) { @default_store }+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }+ let(:names) { Spree::AgentTools::OperationCatalog.all.map(&:name) }++ def tool(name)+ Spree.admin_agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }+ end++ def every_schema+ catalog = Spree::AgentTools::OperationCatalog+ (catalog.all + catalog.aliases).map(&:input_schema)+ end++ describe 'the catalog' do+ it 'offers a tool for each non-CRUD admin write' do+ expect(names).to include('orders_cancel', 'payments_capture', 'sellers_approve', 'stock_transfers_mark_ready')+ end++ # Creates of a resource that lives under two parents, which the generic+ # create cannot choose between, named explicitly.+ it 'offers a create that names its tool' do+ expect(names).to include('stock_transfers_receive', 'purchase_orders_receive', 'shipping_labels_purchase')+ end++ it 'no longer answers to deliveries_update_tracking, which marked a delivery delivered' do+ expect(Spree.admin_agent_tools.find_for('deliveries_update_tracking', context)).to be_nil+ end++ it 'offers the product status moves, which now have endpoints' do+ expect(names).to include('products_activate', 'products_archive', 'products_draft')+ end++ it 'leaves plain create, update and destroy to the generic tools' do+ expect(names).not_to include('products_create', 'products_update', 'orders_destroy')+ end++ it 'leaves out an operation its spec opts out' do+ expect(names).not_to include('customers_anonymize', 'products_bulk_destroy', 'stock_levels_bulk_upsert')+ end++ it 'gates each tool with its controller\'s write scope' do+ expect(Spree::AgentTools::OperationCatalog.find('payments_capture').permission).to eq('write_payments')+ expect(Spree::AgentTools::OperationCatalog.find('orders_cancel').permission).to eq('write_orders')+ end++ it 'describes a tool in the operation\'s own words' do+ expect(tool('orders_cancel').description).to start_with('Cancel an order. Cancels a completed order.')+ end++ it 'offers nothing to a key without the scope' do+ reader = create(:api_key, :secret, store: store, scopes: ['read_orders'])+ reader_context = Spree::AgentTools::Context.new(store: store, api_key: reader,+ request_headers: agent_headers_for_key(reader))++ offered = Spree.admin_agent_tools.available_for(reader_context).map(&:tool_name)++ expect(offered).not_to include('orders_cancel')+ end+ end++ describe 'the input schema' do+ it 'is the path segments beside the request body' do+ properties = tool('orders_cancel').class.input_schema['properties']++ expect(properties.keys).to include('id', 'cancel_reason_id', 'cancel_note', 'notify_customer')+ end++ it 'keeps a segment required when it is the record the call is about' do+ expect(tool('catalog_quantity_rules_upsert').class.input_schema['required']).to include('catalog_id')+ end++ it 'carries a nested body shape whole' do+ prices = tool('prices_bulk_upsert').class.input_schema.dig('properties', 'prices')++ expect(prices['type']).to eq('array')+ expect(prices.dig('items', 'properties')).to include('variant_id', 'amount')+ end++ it 'is plain JSON Schema, with no reference or OpenAPI-only keyword left in it' do+ serialized = JSON.generate(every_schema)++ expect(serialized).not_to include('$ref', '"nullable"')+ end+ end++ describe 'a call' do+ it 'runs the operation through its endpoint' do+ order = create(:order_ready_to_ship, store: store)++ result = tool('orders_cancel').call(id: order.prefixed_id, cancel_note: 'Duplicate order')++ expect(result[:error]).to be_nil+ expect(order.reload.status).to eq('canceled')+ expect(result[:summary]).to eq("Cancel an order #{order.number}")+ end++ it 'does not reach a record in another store' do+ theirs = create(:order_ready_to_ship, store: create(:store, code: "other-#{SecureRandom.hex(4)}"))++ result = tool('orders_cancel').call(id: theirs.prefixed_id)++ expect(result[:error]).to be_present+ expect(theirs.reload.status).not_to eq('canceled')+ end++ # The caller named the payment; the order it belongs to follows from it.+ it 'reads a parent segment off the record the call names' do+ order = create(:order_with_line_items, store: store)+ payment = create(:payment, order: order, amount: 10)++ result = tool('payments_void').call(id: payment.prefixed_id)++ expect(result[:error]).to be_nil+ expect(payment.reload.status).to eq('void')+ end++ it 'names back an argument the operation does not take' do+ order = create(:order_ready_to_ship, store: store)++ result = tool('orders_cancel').call(id: order.prefixed_id, reason_code: 'duplicate')++ expect(result[:error]).to include('reason_code')+ expect(result[:accepted_arguments]).to include('cancel_reason_id')+ expect(order.reload.status).not_to eq('canceled')+ end++ it 'asks for a segment it was not given' do+ expect(tool('orders_cancel').call[:error]).to include('needs id')+ end++ it 'moves a product through its status workflow' do+ product = create(:product, store: store, status: 'active')++ result = tool('products_draft').call(id: product.prefixed_id)++ expect(result[:error]).to be_nil+ expect(product.reload.status).to eq('draft')+ end++ it 'shows the operation and its record before running' do+ expect(tool('orders_cancel').summary(id: 'or_123')).to eq('Cancel an order or_123')+ end+ end++ # A read becomes a tool only when its spec opts it in; it then answers+ # with what it read and takes its arguments as the query.+ describe 'an opted-in read' do+ let(:entry) do+ Spree::AgentTools::OperationCatalog::Entry.new(+ name: 'promotion_rules_types', verb: 'get', path: '/api/v3/admin/promotion_rules/types',+ description: 'List promotion rule types', summary: 'List promotion rule types',+ permission: 'read_promotions', resource_key: 'promotion_rules', path_params: [],+ body_properties: {}, body_required: [], path_descriptions: {},+ listed: true, legacy_parameters: {}+ )+ end++ it 'returns the data the endpoint answered with' do+ result = described_class.for(entry).new(context).call++ expect(result[:error]).to be_nil+ expect(result[:data]).to be_present+ end+ end++ describe 'describe_resource' do+ it 'names the parent a resource is written under' do+ described = tool('describe_resource').call(resource: 'variants')++ expect(described[:resources].first[:parent]).to eq('products')+ end+ end++ # The 6.0.0 tools took a workflow's keywords. Through 6.0.x those calls keep+ # working, and the result says what to send instead.+ describe 'a call written for 6.0.0' do+ it 'maps a renamed parameter and says so' do+ order = create(:order_ready_to_ship, store: store)+ reason = store.order_cancellation_reasons.first || create(:order_cancellation_reason, store: store)++ result = tool('orders_cancel').call(order: order.prefixed_id, reason: reason.prefixed_id)++ expect(result[:error]).to be_nil+ expect(order.reload.cancel_reason_id).to eq(reason.id)+ expect(result[:deprecations]).to include('order is deprecated: use id.',+ 'reason is deprecated: use cancel_reason_id.')+ end++ it 'keeps the note about an old name when the call is refused' do+ result = tool('orders_cancel').call(order: 'or_nope')++ expect(result[:error]).to be_present+ expect(result[:deprecations]).to include('order is deprecated: use id.')+ end++ it 'ignores a parameter the endpoint never read, and says so' do+ order = create(:order_ready_to_ship, store: store)++ result = tool('orders_cancel').call(order: order.prefixed_id, canceled_at: Time.current.iso8601)++ expect(result[:error]).to be_nil+ expect(result[:deprecations]).to include(a_string_including('canceled_at', 'ignored'))+ end++ it 'still answers to a name no longer listed' do+ product = create(:product, store: store)+ sku = "SKU-#{SecureRandom.hex(3)}"++ old = Spree.admin_agent_tools.find_for('variants_create', context)+ result = old.call(product: product.prefixed_id, attributes: { 'sku' => sku })++ expect(names).not_to include('variants_create')+ expect(result[:error]).to be_nil+ expect(Spree::Variant.where(sku: sku)).to exist+ end++ it 'ignores an attributes argument that is not a hash, and says so' do+ product = create(:product, store: store)++ old = Spree.admin_agent_tools.find_for('variants_create', context)+ result = old.call(product: product.prefixed_id, attributes: '{"sku":"X1"}')++ expect(result[:deprecations]).to include(a_string_including('attributes', 'ignored'))+ end++ it 'names the record on the approval line when called by old names' do+ expect(tool('orders_cancel').summary(order: 'or_123')).to eq('Cancel an order or_123')+ end++ it 'fills a parent segment from the record an old parameter named' do+ order = create(:order_ready_to_ship, store: store)++ old = Spree.admin_agent_tools.find_for('shipping_labels_purchase', context)+ result = old.call(owner: order.fulfillments.first.prefixed_id)++ # The provider refuses in test, which is the endpoint answering — an+ # unfilled segment would have been refused before the request.+ expect(result[:error]).not_to match(/needs|not found/i)+ end+ end++ describe 'Registry#expose_workflows' do+ it 'is deprecated and changes nothing' do+ registry = Spree::AgentTools::Registry.new(audience: :admin)+ allow(Spree::Deprecation).to receive(:warn)++ registry.expose_workflows(order_cancel_workflow: 'write_orders')++ expect(Spree::Deprecation).to have_received(:warn).with(a_string_including('expose_workflows is deprecated'))+ expect(registry.exposed_workflows.keys).to eq([:order_cancel_workflow])+ end+ end+enddiff --git a/spree/core/app/tools/spree/agent_tools/describe_resource.rb b/spree/core/app/tools/spree/agent_tools/describe_resource.rbindex 9bd4c0c36b..fc634f00e5 100644--- a/spree/core/app/tools/spree/agent_tools/describe_resource.rb+++ b/spree/core/app/tools/spree/agent_tools/describe_resource.rb@@ -84,6 +84,16 @@ module Spreeentry.writable_attribute_names.presenceend+ # The action tools this caller is offered, by resource, worked out once+ # per call rather than once per resource described.+ def actions_for(entry)+ @actions ||= Spree.admin_agent_tools.to_a.grep(->(klass) { klass < Spree::AgentTools::OperationTool }).+ select { |klass| context.permitted?(klass.permission) }.+ group_by { |klass| klass.operation.resource_key }.+ transform_values { |classes| classes.map(&:tool_name).sort }+ @actions[entry.key]+ end+def describe(entry, detailed:){resource: entry.key,@@ -97,6 +107,10 @@ module Spree# which is what create_resource and update_resource tell it to do.# Offered only where the caller could actually write.writable_attributes: writable_attributes_for(entry),+ # The action tools that act on this resource — cancel, approve,+ # capture — so a model that found an order learns what it can do+ # to one without scanning the whole tool list.+ actions: actions_for(entry),# What goes inside a list-valued attribute. Without it a model sees# `variants` and has no idea a whole variant fits there, so it# creates the product and then adds each variant separately.diff --git a/spree/core/lib/spree/agent_tool.rb b/spree/core/lib/spree/agent_tool.rbindex 7957a0a88f..d83a90d723 100644--- a/spree/core/lib/spree/agent_tool.rb+++ b/spree/core/lib/spree/agent_tool.rb@@ -111,6 +111,44 @@ class AgentTooldef paramsdeclared_paramsend++ # The declared params as JSON Schema, which is what an adapter hands a+ # client. A tool built from an OpenAPI operation overrides this with the+ # operation's own schema, nested properties included.+ #+ # @return [Hash]+ def input_schema+ properties = params.to_h do |name, options|+ property = { 'type' => json_type(options[:type]) }+ property['description'] = options[:description] if options[:description].present?+ # An array must say what it holds: a client validating arguments+ # against the schema refuses the call otherwise.+ property['items'] = { 'type' => json_type(options[:items] || :string) } if property['type'] == 'array'++ [name.to_s, property]+ end++ {+ 'type' => 'object',+ 'properties' => properties,+ 'required' => params.select { |_name, options| options[:required] }.keys.map(&:to_s)+ }+ end++ private++ # A tool declares Ruby-ish types; JSON Schema wants its own names, and+ # anything unrecognised is a string, which every client can render.+ def json_type(type)+ case type&.to_sym+ when :boolean then 'boolean'+ when :integer then 'integer'+ when :number, :float, :decimal then 'number'+ when :object, :hash then 'object'+ when :array then 'array'+ else 'string'+ end+ endend# @return [Spree::AgentTools::Context] who is asking, and wherediff --git a/spree/core/lib/spree/agent_tools.rb b/spree/core/lib/spree/agent_tools.rbindex 0517c4a76f..ccc0125313 100644--- a/spree/core/lib/spree/agent_tools.rb+++ b/spree/core/lib/spree/agent_tools.rb@@ -3,10 +3,10 @@ require 'spree/agent_tools/context'require 'spree/agent_tools/resource_map'require 'spree/agent_tools/api_dispatch'require 'spree/agent_tools/membership_map'-require 'spree/agent_tools/workflow_endpoints'require 'spree/agent_tools/record_summary'-require 'spree/agent_tools/workflow_schema'-require 'spree/agent_tools/workflow_tool'+require 'spree/agent_tools/legacy_tools'+require 'spree/agent_tools/operation_catalog'+require 'spree/agent_tools/operation_tool'require 'spree/agent_tools/default_catalog'module Spreediff --git a/spree/core/lib/spree/agent_tools/default_catalog.rb b/spree/core/lib/spree/agent_tools/default_catalog.rbindex f5d050cf3b..8a79bb3832 100644--- a/spree/core/lib/spree/agent_tools/default_catalog.rb+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb@@ -1,15 +1,11 @@module Spreemodule AgentTools- # The tools Spree ships: the generic read tools, and the workflows exposed- # as write tools.+ # The hand-written tools Spree ships: the generic reads and writes,+ # reporting, imports, files and stock.#- # The write allowlist is the whole catalog of back-office writes an agent- # may make. Every entry names a `Spree::Dependencies` key, so a host app- # that swaps in its own workflow class keeps the tool and gets the- # replacement's schema; and a permission, which must equal the write scope- # of the admin controller that invokes the same workflow — a contract spec- # in `spree_api` fails when the two disagree, or when a controller gains a- # workflow that is neither listed here nor excluded below.+ # Back-office actions are not listed here. Every Admin API action is a+ # tool built from its OpenAPI operation ({OperationCatalog}); an action+ # that should not be one is marked in its rswag spec, with the reason.module DefaultCatalog# Read tools, and the writes that are not workflows.TOOLS = %w[@@ -33,7 +29,9 @@ module Spree].freeze- # Workflow key => permission, or => {permission:, except:, summary:}.+ # @deprecated The 6.0.0 workflow allowlist, kept only so a reference to+ # it does not break through 6.0.x. Nothing reads it: Admin API+ # operations are tools on their own. Removed in 6.1.WORKFLOWS = {# Catalogproduct_activate_workflow: 'write_products',@@ -99,9 +97,9 @@ module Spreetax_exemption_certificate_verify_workflow: 'write_customers'}.freeze- # Workflows an admin controller invokes that are deliberately NOT tools,- # each with the reason. The contract spec reads this list, so a workflow- # can never be quietly dropped: it is exposed, or it is here.+ # @deprecated The 6.0.0 exclusion list, kept like {WORKFLOWS}. Its+ # reasons now travel as `agent_tool false, reason:` on the operation's+ # rswag spec. Removed in 6.1.# The email template editor is a draft-and-publish surface: its steps# move a draft through revisions against a live preview, and they mean# nothing outside that screen. Publishing one sends real mail in the@@ -168,9 +166,10 @@ module Spree# @return [void]def install(registry)TOOLS.each { |tool| registry << tool }- registry.expose_workflows(**WORKFLOWS)endend++ deprecate_constant :WORKFLOWS, :EXCLUDED_WORKFLOWSendendenddiff --git a/spree/core/lib/spree/agent_tools/legacy_tools.rb b/spree/core/lib/spree/agent_tools/legacy_tools.rbnew file mode 100644index 0000000000..dbb98a8ad3--- /dev/null+++ b/spree/core/lib/spree/agent_tools/legacy_tools.rb@@ -0,0 +1,212 @@+module Spree+ module AgentTools+ # The workflow tools Spree 6.0.0 offered, by the name and parameters a+ # client saw then, and the operation each now runs.+ #+ # 6.0.0 derived a tool from a workflow's `perform` signature, so its+ # parameters were the workflow's keywords (`order`, `reason`); a tool now+ # takes the operation's own (`id`, `cancel_reason_id`). This table, written+ # once from the 6.0.0 schemas, keeps those calls working through 6.0.x. It+ # is an explicit list, not a rule: nothing here guesses one name from+ # another.+ #+ # A parameter mapped to nil never reached the endpoint in 6.0.0 either; it+ # is ignored, and the result says so. One mapped to `:merge` was a hash of+ # fields, merged into the body, which is what 6.0.0 did with it.+ #+ # `deliveries_update_tracking` is not here: 6.0.0 sent it to the+ # mark-delivered endpoint and dropped its tracking fields, so a call meant+ # to record tracking marked the delivery delivered. No endpoint sets a+ # carrier status, so the name no longer answers rather than doing that.+ #+ # Removed in 6.1, with the names that are no longer listed.+ # See docs/plans/6.0-agent-tools-from-openapi.md.+ module LegacyTools+ # Old tool name => the operation it runs and its renamed parameters.+ TOOLS = {+ 'catalogs_activate' => {+ verb: 'patch', path: '/api/v3/admin/catalogs/{id}/activate',+ parameters: { 'catalog' => 'id' }+ },+ 'catalogs_deactivate' => {+ verb: 'patch', path: '/api/v3/admin/catalogs/{id}/deactivate',+ parameters: { 'catalog' => 'id' }+ },+ 'fulfillments_create' => {+ verb: 'post', path: '/api/v3/admin/orders/{order_id}/fulfillments',+ parameters: {+ 'order' => 'order_id', 'stock_location' => 'stock_location_id',+ 'source_fulfillment' => 'source_fulfillment_id', 'delivery_method' => 'delivery_method_id'+ }+ },+ 'fulfillments_mark_delivered' => {+ verb: 'patch', path: '/api/v3/admin/orders/{order_id}/fulfillments/{id}/mark_delivered',+ parameters: { 'fulfillment' => 'id' }+ },+ 'orders_cancel' => {+ verb: 'patch', path: '/api/v3/admin/orders/{id}/cancel',+ parameters: { 'order' => 'id', 'canceled_at' => nil, 'reason' => 'cancel_reason_id', 'note' => 'cancel_note' }+ },+ 'orders_complete' => {+ verb: 'patch', path: '/api/v3/admin/orders/{id}/complete',+ parameters: { 'order' => 'id' }+ },+ 'payments_capture' => {+ verb: 'patch', path: '/api/v3/admin/orders/{order_id}/payments/{id}/capture',+ parameters: { 'payment' => 'id' }+ },+ 'payments_void' => {+ verb: 'patch', path: '/api/v3/admin/orders/{order_id}/payments/{id}/void',+ parameters: { 'payment' => 'id' }+ },+ 'price_lists_activate' => {+ verb: 'patch', path: '/api/v3/admin/price_lists/{id}/activate',+ parameters: { 'price_list' => 'id' }+ },+ 'price_lists_deactivate' => {+ verb: 'patch', path: '/api/v3/admin/price_lists/{id}/deactivate',+ parameters: { 'price_list' => 'id' }+ },+ 'products_activate' => {+ verb: 'patch', path: '/api/v3/admin/products/{id}/activate',+ parameters: { 'product' => 'id' }+ },+ 'products_approve' => {+ verb: 'patch', path: '/api/v3/admin/products/{id}/approve',+ parameters: { 'product' => 'id' }+ },+ 'products_archive' => {+ verb: 'patch', path: '/api/v3/admin/products/{id}/archive',+ parameters: { 'product' => 'id' }+ },+ 'products_draft' => {+ verb: 'patch', path: '/api/v3/admin/products/{id}/draft',+ parameters: { 'product' => 'id' }+ },+ 'products_reject' => {+ verb: 'patch', path: '/api/v3/admin/products/{id}/reject',+ parameters: { 'product' => 'id' }+ },+ 'purchase_orders_cancel' => {+ verb: 'patch', path: '/api/v3/admin/purchase_orders/{id}/cancel',+ parameters: { 'purchase_order' => 'id' }+ },+ 'purchase_orders_close' => {+ verb: 'patch', path: '/api/v3/admin/purchase_orders/{id}/close',+ parameters: { 'purchase_order' => 'id' }+ },+ 'purchase_orders_mark_draft' => {+ verb: 'patch', path: '/api/v3/admin/purchase_orders/{id}/mark_draft',+ parameters: { 'purchase_order' => 'id' }+ },+ 'purchase_orders_mark_ordered' => {+ verb: 'patch', path: '/api/v3/admin/purchase_orders/{id}/mark_ordered',+ parameters: { 'purchase_order' => 'id' }+ },+ 'purchase_orders_receive' => {+ verb: 'post', path: '/api/v3/admin/purchase_orders/{purchase_order_id}/stock_receipts',+ parameters: { 'purchase_order' => 'purchase_order_id' }+ },+ 'refunds_create' => {+ verb: 'post', path: '/api/v3/admin/orders/{order_id}/refunds',+ parameters: {+ 'payment' => 'payment_id', 'reason' => 'refund_reason_id', 'originator' => nil,+ 'order' => 'order_id', 'tax_amount' => nil+ }+ },+ 'seller_requirement_submissions_accept' => {+ verb: 'patch', path: '/api/v3/admin/sellers/{seller_id}/requirement_submissions/{id}/accept',+ parameters: { 'submission' => 'id' }+ },+ 'seller_requirement_submissions_reject' => {+ verb: 'patch', path: '/api/v3/admin/sellers/{seller_id}/requirement_submissions/{id}/reject',+ parameters: { 'submission' => 'id' }+ },+ 'seller_requirement_submissions_waive' => {+ verb: 'post', path: '/api/v3/admin/sellers/{seller_id}/requirement_submissions',+ parameters: { 'seller' => 'seller_id', 'requirement' => 'requirement_id' }+ },+ 'sellers_approve' => {+ verb: 'patch', path: '/api/v3/admin/sellers/{id}/approve',+ parameters: { 'seller' => 'id' }+ },+ 'sellers_invite' => {+ verb: 'post', path: '/api/v3/admin/sellers/{id}/invite',+ parameters: { 'seller' => 'id', 'inviter' => nil, 'role' => 'role_id' }+ },+ 'sellers_reject' => {+ verb: 'patch', path: '/api/v3/admin/sellers/{id}/reject',+ parameters: { 'seller' => 'id' }+ },+ 'sellers_reopen_onboarding' => {+ verb: 'patch', path: '/api/v3/admin/sellers/{id}/reopen_onboarding',+ parameters: { 'seller' => 'id' }+ },+ 'sellers_suspend' => {+ verb: 'patch', path: '/api/v3/admin/sellers/{id}/suspend',+ parameters: { 'seller' => 'id' }+ },+ 'shipping_labels_purchase' => {+ verb: 'post', path: '/api/v3/admin/orders/{order_id}/fulfillments/{fulfillment_id}/labels',+ parameters: { 'owner' => 'fulfillment_id' }+ },+ 'shipping_labels_refund' => {+ verb: 'patch', path: '/api/v3/admin/orders/{order_id}/fulfillments/{fulfillment_id}/labels/{id}/refund',+ parameters: { 'shipping_label' => 'id' }+ },+ 'stock_transfers_cancel' => {+ verb: 'patch', path: '/api/v3/admin/stock_transfers/{id}/cancel',+ parameters: { 'stock_transfer' => 'id' }+ },+ 'stock_transfers_close' => {+ verb: 'patch', path: '/api/v3/admin/stock_transfers/{id}/close',+ parameters: { 'stock_transfer' => 'id' }+ },+ 'stock_transfers_mark_draft' => {+ verb: 'patch', path: '/api/v3/admin/stock_transfers/{id}/mark_draft',+ parameters: { 'stock_transfer' => 'id' }+ },+ 'stock_transfers_mark_in_transit' => {+ verb: 'patch', path: '/api/v3/admin/stock_transfers/{id}/mark_in_transit',+ parameters: { 'stock_transfer' => 'id' }+ },+ 'stock_transfers_mark_ready' => {+ verb: 'patch', path: '/api/v3/admin/stock_transfers/{id}/mark_ready',+ parameters: { 'stock_transfer' => 'id' }+ },+ 'stock_transfers_receive' => {+ verb: 'post', path: '/api/v3/admin/stock_transfers/{stock_transfer_id}/stock_receipts',+ parameters: { 'stock_transfer' => 'stock_transfer_id' }+ },+ 'tax_exemption_certificates_verify' => {+ verb: 'patch', path: '/api/v3/admin/companies/{company_id}/tax_exemption_certificates/{id}/verify',+ parameters: { 'certificate' => 'id' }+ },+ 'variants_create' => {+ verb: 'post', path: '/api/v3/admin/products/{product_id}/variants',+ parameters: { 'product' => 'product_id', 'attributes' => :merge }+ },+ 'variants_update' => {+ verb: 'patch', path: '/api/v3/admin/products/{product_id}/variants/{id}',+ parameters: { 'variant' => 'id', 'attributes' => :merge }+ }+ }.freeze++ class << self+ # The 6.0.0 parameters of a tool that keeps its name, when it still+ # runs the same operation.+ #+ # @param name [String]+ # @param verb [String]+ # @param path [String] the OpenAPI path+ # @return [Hash{String => String, Symbol, nil}]+ def parameters_for(name, verb, path)+ tool = TOOLS[name.to_s]+ return {} unless tool && tool[:verb] == verb.to_s && tool[:path] == path++ tool[:parameters]+ end+ end+ end+ end+enddiff --git a/spree/core/lib/spree/agent_tools/operation_catalog.rb b/spree/core/lib/spree/agent_tools/operation_catalog.rbnew file mode 100644index 0000000000..e2406d3dbf--- /dev/null+++ b/spree/core/lib/spree/agent_tools/operation_catalog.rb@@ -0,0 +1,206 @@+module Spree+ module AgentTools+ # Every Admin API operation an agent may call by name, and what it takes.+ #+ # A contract like {ResourceMap}: core declares the shape, and `spree_api`+ # fills it from the Admin API's OpenAPI document — core's and every+ # extension's — and the routes behind it. An operation that gains an+ # endpoint is a tool in the same commit, with the summary, description and+ # request body its rswag spec wrote.+ #+ # See docs/plans/6.0-agent-tools-from-openapi.md.+ module OperationCatalog+ # @!attribute name+ # @return [String] the tool name, `orders_cancel`+ # @!attribute verb+ # @return [String] 'post', 'patch', 'put', 'delete' or 'get'+ # @!attribute path+ # @return [String] the OpenAPI path, with `{name}` segments+ # @!attribute description+ # @return [String] what the model reads when choosing the tool+ # @!attribute summary+ # @return [String] the operation summary, for the confirmation line+ # @!attribute permission+ # @return [String] the scope gating it, from the routed controller+ # @!attribute resource_key+ # @return [String, nil] the resource-map key of the routed controller's+ # model, so a parent segment can be read off the record+ # @!attribute path_params+ # @return [Array<String>] the dynamic segments, in path order+ # @!attribute body_properties+ # @return [Hash{String => Hash}] the request body's JSON Schema+ # properties, references inlined+ # @!attribute body_required+ # @return [Array<String>]+ # @!attribute path_descriptions+ # @return [Hash{String => String}]+ # @!attribute listed+ # @return [Boolean] false for a 6.0.0 name kept callable through 6.0.x+ # @!attribute legacy_parameters+ # @return [Hash{String => String, nil}] 6.0.0 parameter => its name now+ Entry = Struct.new(:name, :verb, :path, :description, :summary, :permission, :resource_key,+ :path_params, :body_properties, :body_required, :path_descriptions,+ :listed, :legacy_parameters, keyword_init: true) do+ # @return [Boolean] a read opted in to the catalog+ def read?+ verb == 'get'+ end++ # @return [Boolean] whether the call changes the store+ def mutating+ !read?+ end++ # The resource each `{x_id}` segment names, read off the path itself —+ # `/orders/{order_id}/items` names `orders` — so a renamed nested+ # route still points at the right resource.+ #+ # @return [Hash{String => String}] segment => resource key+ def segment_keys+ path.scan(%r{/([a-z_]+)/\{([a-z_]+_id)\}}).to_h { |key, segment| [segment, key] }+ end++ # The segments a call may leave out, read off the record a later+ # segment names. The innermost is the record the call is about, never+ # one to read off another.+ #+ # @return [Hash{String => String}] segment => resource key+ def parent_keys+ segment_keys.except(path_params.last)+ end++ # @param values [Hash{String => String}] path segment => value+ # @return [String, nil] nil while a segment is unfilled+ def path_for(values)+ filled = path.gsub(/\{([a-z_]+)\}/) do+ value = values[Regexp.last_match(1)]+ value.present? ? ERB::Util.url_encode(value.to_s) : Regexp.last_match(0)+ end+ filled unless filled.include?('{')+ end++ # The tool's arguments as JSON Schema: the path segments and the+ # request body, side by side.+ #+ # A segment or field a 6.0.0 name still reaches is left out of+ # `required` through 6.0.x — a client validating against the schema+ # would otherwise refuse the old name before the tool could map it —+ # and so is a parent segment, which the tool can read off the record+ # the call names. The tool checks both itself.+ #+ # @return [Hash]+ def input_schema+ properties = path_params.to_h do |segment|+ [segment, { 'type' => 'string', 'description' => path_descriptions[segment] }.compact]+ end.merge(body_properties)++ aliased = legacy_parameters.values.grep(String)+ parents = parent_keys.keys+ # A 6.0.0 name no longer listed keeps the 6.0.0 contract, which+ # required nothing the operation's body now does.+ required = listed ? (path_params + body_required).uniq - aliased - parents : []++ { 'type' => 'object', 'properties' => properties, 'required' => required }+ end+ end++ class << self+ # How the catalog fills itself the first time it is read. `spree_api`+ # sets it to its walk over the document; an installation without the+ # API engine has no operations to offer.+ #+ # @return [#call, nil]+ attr_accessor :deriver++ # @return [Array<Entry>] the operations offered by name+ def all+ derive!+ entries.values+ end++ # The 6.0.0 names kept callable through 6.0.x, which no listing shows.+ #+ # @return [Array<Entry>]+ def aliases+ derive!+ alias_entries.values+ end++ # A tool by its name, including a 6.0.0 name no longer listed.+ #+ # @param name [String]+ # @return [Entry, nil]+ def find(name)+ derive!+ entries[name.to_s] || alias_entries[name.to_s]+ end++ # Registers one operation. Re-registering a name replaces it, because+ # the walk runs again after a code reload.+ #+ # @return [Entry]+ def register(**attributes)+ entry = build(listed: true, **attributes)+ entries[entry.name] = entry+ end++ # Registers a 6.0.0 name for an operation, callable but not listed.+ # A name an offered operation already has keeps that operation.+ #+ # @return [Entry, nil]+ def register_alias(**attributes)+ entry = build(**attributes, listed: false)+ alias_entries[entry.name] = entry unless entries.key?(entry.name)+ end++ # @return [void]+ def reset!+ @entries = {}+ @alias_entries = {}+ end++ # Marks the catalog for rebuilding on its next read.+ #+ # @return [void]+ def stale!+ @derived = false+ end++ # Fills the catalog once, under a mutex. The flag is set only once the+ # deriver has finished, so a second reader waits on the mutex instead+ # of reading a catalog the deriver has just emptied. Nothing the+ # deriver calls reads the catalog back, so it cannot recurse.+ #+ # @return [void]+ def derive!+ return if @derived || deriver.nil?++ derive_mutex.synchronize do+ next if @derived++ deriver.call+ @derived = true+ end+ end++ private++ def build(**attributes)+ Entry.new(legacy_parameters: {}, body_properties: {}, body_required: [], path_descriptions: {}, **attributes)+ end++ def entries+ @entries ||= {}+ end++ def alias_entries+ @alias_entries ||= {}+ end++ def derive_mutex+ @derive_mutex ||= Mutex.new+ end+ end+ end+ end+enddiff --git a/spree/core/lib/spree/agent_tools/operation_tool.rb b/spree/core/lib/spree/agent_tools/operation_tool.rbnew file mode 100644index 0000000000..6fcc4d383a--- /dev/null+++ b/spree/core/lib/spree/agent_tools/operation_tool.rb@@ -0,0 +1,189 @@+module Spree+ module AgentTools+ # One agent tool per Admin API operation in {OperationCatalog}.+ #+ # Everything about the tool is the operation's: its name, its prose, its+ # arguments and the request it sends. The arguments are the path segments+ # and the request body under the names the document gives them, so a call+ # is a request with no translation step between what the model was shown+ # and what the endpoint receives. The endpoint runs its own routing,+ # authentication, scope check, record-level ability and workflow.+ #+ # Generated classes are cached per entry, so a catalog rebuilt after a+ # code reload produces new tools rather than serving stale ones.+ #+ # See docs/plans/6.0-agent-tools-from-openapi.md.+ class OperationTool < Spree::AgentTool+ class_attribute :operation, instance_accessor: false++ class << self+ # @param entry [OperationCatalog::Entry]+ # @return [Class<OperationTool>]+ def for(entry)+ # By identity: an entry is rebuilt, as a new object, whenever the+ # catalog is, and hashing one walks its whole request schema.+ cache[entry] ||= Class.new(self) do+ self.operation = entry++ tool_name entry.name+ description entry.description+ permission entry.permission+ mutating! if entry.mutating+ end+ end++ # @return [Hash] JSON Schema for the arguments, read by the adapters+ def input_schema+ @input_schema ||= operation.input_schema+ end++ # @return [void]+ def clear_cache!+ @cache = {}+ end++ private++ def cache+ @cache ||= {}.compare_by_identity+ end+ end++ delegate :operation, to: :class++ # @return [Hash] the result handed back to the model+ def call(**arguments)+ arguments, notes = map_legacy_arguments(arguments.transform_keys(&:to_s))++ segments = operation.path_params.index_with { |segment| arguments[segment] }+ derive_parents(segments)+ path = operation.path_for(segments)+ # Only what the path needs is checked here. What the body requires is+ # the endpoint's to refuse, in its own words.+ if path.nil?+ unfilled = segments.select { |_segment, value| value.blank? }.keys+ return { error: "#{tool_name} needs #{unfilled.to_sentence}.", deprecations: notes.presence }.compact+ end++ values, refusal = body_for(arguments)+ return refusal.merge(deprecations: notes.presence).compact if refusal++ response = dispatch(path, values)+ return { error: response.error_message, deprecations: notes.presence }.compact unless response.success?++ # A read opted in to the catalog answers with what it read, filtered+ # like every other record that leaves for a model.+ return { summary: operation.summary, data: sanitized(response.data) } if operation.read?++ record = payload_summary(response.data)+ named = record&.dig(:title).presence || record&.dig(:id).presence || record&.dig('id').presence+ { summary: named ? "#{operation.summary} #{named}" : summary(arguments), record: record,+ deprecations: notes.presence }.compact+ end++ # The line a client shows before the call runs: the operation's own+ # summary and the records it names.+ #+ # @param arguments [Hash]+ # @return [String]+ def summary(arguments)+ arguments, = map_legacy_arguments(arguments.transform_keys(&:to_s))+ named = operation.path_params.filter_map { |segment| arguments[segment] }+ [operation.summary, named.reverse.join(' ').presence].compact.join(' ')+ end++ private++ # 6.0.0 names (`order`, `reason`) mapped to the operation's (`id`,+ # `cancel_reason_id`), with a note per name so the model learns the new+ # one. A name the endpoint never read is dropped and said to be.+ def map_legacy_arguments(arguments)+ renames = operation.legacy_parameters+ return [arguments, []] if renames.blank?++ notes = []+ mapped = arguments.each_with_object({}) do |(name, value), result|+ next result[name] = value unless renames.key?(name)++ target = renames[name]+ if target == :merge && value.is_a?(Hash)+ notes << "#{name} is deprecated: send its fields as arguments of their own."+ result.merge!(value.transform_keys(&:to_s)) { |_key, given, _merged| given }+ elsif target.nil? || target == :merge+ notes << "#{name} is not something #{tool_name} sets, and was ignored."+ else+ notes << "#{name} is deprecated: use #{target}."+ result[target] = value unless result.key?(target)+ end+ end++ [mapped, notes]+ end++ # A parent segment the caller left out, read off a record the call+ # does name — a payment's order, a fulfillment's order — through the+ # resource map, under the caller's store. Only a record the caller may+ # read is consulted; anything else stays unfilled and is asked for.+ def derive_parents(segments)+ missing = operation.parent_keys.keys.select { |segment| segments[segment].blank? }+ return if missing.empty?++ records = segments.compact_blank.to_a.reverse.filter_map { |segment, id| record_for(segment, id) }+ missing.reverse_each do |segment|+ parent = records.lazy.filter_map { |record| record.try(segment.delete_suffix('_id')) }.first+ next if parent.nil?++ segments[segment] = parent.try(:prefixed_id)+ records << parent+ end+ end++ def record_for(segment, id)+ key = segment == 'id' ? operation.resource_key : operation.segment_keys[segment]+ entry = key && ResourceMap.find(key)+ return if entry.nil? || !context.permitted?(entry.permission)++ entry.scope_for(context).find_by_prefix_id(id)+ rescue StandardError+ nil+ end++ def dispatch(path, values)+ dispatcher = ApiDispatch.new(context)+ return dispatcher.call(method: :get, path: path, params: values || {}) if operation.read?++ dispatcher.call(method: operation.verb.to_sym, path: path, body: values)+ end++ # What travels as the body, or a read's query: every argument that is+ # not a path segment, checked against the document so a guessed field is+ # named back rather than dropped behind a success.+ def body_for(arguments)+ body = arguments.except(*operation.path_params)+ return [nil, nil] if body.empty?++ accepted = operation.body_properties.keys+ unknown = body.keys - accepted+ return [body, nil] if unknown.empty?++ [nil, { error: "#{tool_name} does not accept #{unknown.to_sentence}.",+ accepted_arguments: (operation.path_params + accepted).sort }]+ end++ # The record the endpoint returned, compacted and filtered the way a+ # record read from the map is.+ def payload_summary(data)+ return unless data.is_a?(Hash)++ entry = operation.resource_key && ResourceMap.find(operation.resource_key)+ return sanitized(data).slice('id').presence if entry.nil?++ RecordSummary.from_payload(entry: entry, payload: data)+ end++ def sanitized(data)+ RecordSummary.sanitize(data, operation.resource_key)+ end+ end+ end+enddiff --git a/spree/core/lib/spree/agent_tools/registry.rb b/spree/core/lib/spree/agent_tools/registry.rbindex 7b02ccadbb..b35dc2ad78 100644--- a/spree/core/lib/spree/agent_tools/registry.rb+++ b/spree/core/lib/spree/agent_tools/registry.rb@@ -18,10 +18,9 @@ module Spree# 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`- # key and derives each tool from the workflow's own `perform` signature —- # see {#expose_workflows}.+ # Writes are not registered as classes. Every Admin API action an admin+ # key may call is already a tool, built from its OpenAPI operation by+ # {OperationCatalog} — see docs/plans/6.0-agent-tools-from-openapi.md.class Registryinclude Enumerable@@ -61,38 +60,54 @@ module Spreeto_a.each(&)end- # Exposes workflows as write tools, keyed by `Spree::Dependencies` key so- # the tool follows whatever class the host app has registered:- #- # Spree.admin_agent_tools.expose_workflows(- # order_cancel_workflow: 'write_orders',- # product_activate_workflow: 'write_products'- # )- #- # A value may be the permission key on its own, or a hash carrying it- # alongside `except:` (parameters to hide, such as a deprecated one) and- # `summary:` (a callable overriding the generated confirmation line).+ # @deprecated Admin API operations are agent tools on their own, built+ # from the OpenAPI document, so there is nothing to expose. A+ # workflow behind a documented endpoint is that endpoint's tool; one+ # without is not offered. Recorded and otherwise ignored, and removed+ # in 7.0.## @param exposures [Hash{Symbol => String, Hash}]# @return [self]def expose_workflows(**exposures)- exposures.each do |dependency_key, options|- options = { permission: options } if options.is_a?(String) || options.is_a?(Symbol)- @exposed_workflows[dependency_key.to_sym] = {- permission: options.fetch(:permission).to_s,- except: Array(options[:except]).map(&:to_sym),- summary: options[:summary]- }- end+ Spree::Deprecation.warn(+ 'Spree.admin_agent_tools.expose_workflows is deprecated and has no effect: every documented ' \+ 'Admin API action is an agent tool, built from its OpenAPI operation. A workflow reaches agents ' \+ 'through an admin endpoint whose rswag spec is generated into the openapi/admin.yaml your gem ships. ' \+ 'See docs/plans/6.0-agent-tools-from-openapi.md.'+ )++ @exposed_workflows.merge!(exposures.transform_keys(&:to_sym))selfend- # @return [Hash{Symbol => Hash}] every exposed workflow, by dependency key+ # @deprecated see {#expose_workflows}+ # @return [Hash{Symbol => Hash}] what was passed to {#expose_workflows}attr_reader :exposed_workflows# @return [Array<Class<Spree::AgentTool>>]def to_a- registered_classes + workflow_tool_classes+ registered = registered_classes+ registered + operation_tool_classes(registered.map(&:tool_name))+ end++ # A tool this caller may use, by name — including a 6.0.0 name that is+ # no longer listed but still answers through 6.0.x, so a client that+ # learned it keeps working.+ #+ # @param name [String]+ # @param context [Spree::AgentTools::Context]+ # @return [Spree::AgentTool, nil]+ def find_for(name, context)+ name = name.to_s+ tool_class = registered_classes.find { |klass| klass.tool_name == name }+ if tool_class.nil? && operations?+ entry = Spree::AgentTools::OperationCatalog.find(name)+ tool_class = entry && Spree::AgentTools::OperationTool.for(entry)+ end+ return if tool_class.nil? || (tool_class.try(:audience) && tool_class.audience != audience)++ tool = tool_class.new(context)+ tool if tool.permitted?end# Tools this caller may actually use, instantiated for their context.@@ -118,14 +133,33 @@ module Spreeendend- # One generated tool class per exposed workflow whose dependency key- # still resolves. A key an extension removed simply stops being offered- # rather than breaking the whole catalog.- def workflow_tool_classes- @exposed_workflows.filter_map do |dependency_key, options|- Spree::AgentTools::WorkflowTool.for(dependency_key, **options)+ # One tool per operation the catalog lists. Operations are back-office+ # actions, so only the admin surface offers them.+ #+ # A registered tool keeps its name: an operation claiming the same one+ # would make an MCP server refuse the whole list. The contract spec+ # fails on such a clash; at runtime it is logged, once per name.+ def operation_tool_classes(taken)+ return [] unless operations?++ Spree::AgentTools::OperationCatalog.all.filter_map do |entry|+ next Spree::AgentTools::OperationTool.for(entry) unless taken.include?(entry.name)++ warn_shadowed(entry.name)+ nilendend++ def warn_shadowed(name)+ @shadowed ||= Set.new+ return unless @shadowed.add?(name)++ Rails.logger.warn("[Spree] agent tool #{name} is registered by hand; the operation of that name is not offered")+ end++ def operations?+ audience == :admin+ endendendenddiff --git a/spree/core/lib/spree/agent_tools/workflow_endpoints.rb b/spree/core/lib/spree/agent_tools/workflow_endpoints.rbdeleted file mode 100644index d24479f006..0000000000--- a/spree/core/lib/spree/agent_tools/workflow_endpoints.rb+++ /dev/null@@ -1,88 +0,0 @@-module Spree- module AgentTools- # Which Admin API operation runs each workflow an agent may call.- #- # A contract like {ResourceMap} and {MembershipMap}: core declares the- # shape, and `spree_api` fills it by reading its own routes and- # controllers, so a workflow that gains an endpoint is dispatched without- # anyone editing a list.- #- # A workflow with no entry runs in this process instead. That is not a- # fallback to be relied on — it means the capability has no endpoint yet,- # and the tool is the only way to reach it.- module WorkflowEndpoints- # @!attribute verb- # @return [String] 'POST', 'PATCH'- # @!attribute path- # @return [String] with `:name` segments still in it- # @!attribute body_keys- # @return [Array<String>] what the operation's request body accepts,- # read from the generated OpenAPI document — which is where the- # renames live (a cancellation's `reason:` keyword is- # `cancel_reason_id` on the wire)- Entry = Struct.new(:verb, :path, :body_keys, keyword_init: true) do- # The dynamic segments, in the order the path names them.- #- # @return [Array<String>]- def path_params- @path_params ||= path.scan(/:([a-z_]+)/).flatten- end-- # @param values [Hash] path parameter name => id- # @return [String]- def path_for(values)- path.gsub(/:([a-z_]+)/) { values.fetch(Regexp.last_match(1)).to_s }- end- end-- class << self- # @param key [Symbol] a `Spree::Dependencies` workflow key- # @return [Entry, nil]- def find(key)- derive!- entries[key.to_sym]- end-- # @return [Hash{Symbol => Entry}]- def all- derive!- entries- end-- def register(key:, verb:, path:, body_keys: [])- entries[key.to_sym] = Entry.new(verb: verb.to_s.upcase, path: path,- body_keys: body_keys.map(&:to_s))- end-- def reset!- @entries = {}- @derived = false- end-- # What has been registered so far, without deriving — for the- # deriver itself, which must not ask for what it is producing.- #- # @return [Hash{Symbol => Entry}]- def registered- entries- end-- # Filled on first read rather than at boot: deriving it loads every- # admin controller, which a developer who never runs an agent should- # not pay for on each code reload.- def derive!- return if @derived-- @derived = true- Spree::Api::AgentWorkflowEndpoints.install if defined?(Spree::Api::AgentWorkflowEndpoints)- end-- private-- def entries- @entries ||= {}- end- end- end- end-enddiff --git a/spree/core/lib/spree/agent_tools/workflow_schema.rb b/spree/core/lib/spree/agent_tools/workflow_schema.rbdeleted file mode 100644index dc5c18a5bc..0000000000--- a/spree/core/lib/spree/agent_tools/workflow_schema.rb+++ /dev/null@@ -1,279 +0,0 @@-module Spree- module AgentTools- # Reads a workflow's argument contract and turns it into a JSON parameter- # schema an agent can fill in.- #- # Nothing here is hand-maintained. `Method#parameters` on `perform` names- # every keyword and says which are required; the YARD `@param` block above- # it gives each one a type and a sentence of prose. Both already exist on- # every workflow, because the house style requires them — so a workflow- # gains a parameter and the tool's schema gains it in the same commit.- class WorkflowSchema- # A workflow that cannot be exposed as written. Raised at derivation time- # so the contract spec fails in CI rather than an agent meeting a broken- # tool in production.- class UndocumentedParameterError < StandardError- def initialize(workflow_class, names)- super("#{workflow_class} exposes #{names.join(', ')} without a YARD @param — " \- 'every parameter of an exposed workflow needs a documented type')- end- end-- # Tenancy, which comes from the credential and never from the caller.- # A workflow that takes `store:` is given the context's store; offering- # it would invite a model to name another merchant's store, and the- # answer to "which store" is the API key or the signed-in admin.- CONTEXT_PARAMETERS = %i[store].freeze-- # Actor keywords a workflow takes whose association has not been- # converted to `acted_by` yet — the 6.1 half of- # docs/plans/6.0-action-actors.md. They are principals by the same- # reasoning as the converted ones, so they are injected too; each drops- # off this list as its association converts, and the registry below then- # carries it.- UNCONVERTED_PRINCIPAL_PARAMETERS = %i[- reviewer reviewed_by rejected_by suspended_by verified_by reopened_by- ].freeze-- # YARD type to JSON type. A model type is handled separately — it becomes- # a prefixed-id string resolved through the resource map.- PRIMITIVES = {- 'String' => 'string',- 'Symbol' => 'string',- 'Time' => 'string',- 'DateTime' => 'string',- 'Date' => 'string',- 'Boolean' => 'boolean',- 'TrueClass' => 'boolean',- 'FalseClass' => 'boolean',- 'Integer' => 'integer',- 'Numeric' => 'number',- 'Float' => 'number',- 'BigDecimal' => 'number',- 'Hash' => 'object',- 'Array' => 'array'- }.freeze-- # @return [Class] the workflow this schema describes- attr_reader :workflow_class-- # @param workflow_class [Class]- # @param except [Array<Symbol>] parameters to leave out of the schema- def initialize(workflow_class, except: [])- @workflow_class = workflow_class- @except = except.map(&:to_sym)- end-- # Every parameter the caller may supply, in `perform` order.- #- # @return [Array<Hash>] `{name:, required:, json_type:, model_name:, description:}`- def parameters- @parameters ||= begin- documented = docs- undocumented = keywords.keys - documented.keys - injected_parameters - @except- raise UndocumentedParameterError.new(workflow_class, undocumented) if undocumented.any?-- keywords.filter_map do |name, required|- next if @except.include?(name) || injected_parameters.include?(name)-- build_parameter(name, required, documented.fetch(name))- end- end- end-- # The principal keywords this workflow accepts, so the adapter knows- # which to inject.- #- # @return [Array<Symbol>]- def principal_parameters- keywords.keys & self.class.principal_parameter_names- end-- # The tenancy keywords this workflow accepts.- #- # @return [Array<Symbol>]- def context_parameters- keywords.keys & CONTEXT_PARAMETERS- end-- # Everything filled from the context rather than by the caller.- #- # @return [Array<Symbol>]- def injected_parameters- self.class.principal_parameter_names + CONTEXT_PARAMETERS- end-- private-- # `perform`'s keywords, mapped to whether they are required.- #- # @return [Hash{Symbol => Boolean}]- def keywords- @keywords ||= workflow_class.instance_method(:perform).parameters.filter_map do |kind, name|- [name, kind == :keyreq] if %i[key keyreq].include?(kind)- end.to_h- end-- def build_parameter(name, required, doc)- types = doc[:types]- model_name = types.filter_map { |type| model_name_for(type) }.first-- json_type = model_name ? 'string' : json_type_for(types)-- {- name: name,- required: required,- model_name: model_name,- json_type: json_type,- item_type: json_type == 'array' ? item_type_for(types) : nil,- description: description_for(doc[:description], model_name)- }- end-- def description_for(text, model_name)- return text if model_name.blank?-- prefix = "Prefixed id of the #{model_name.demodulize.underscore.humanize.downcase}"- text.present? ? "#{prefix} — #{text}" : prefix- end-- # A Spree model, addressed by prefixed id, as its canonical class name.- # A YARD block may name a deprecated alias (`Spree::ShippingMethod` for- # `Spree::DeliveryMethod`), and the alias is a constant pointing at the- # same class — so resolve the constant and ask it for its own name- # rather than trusting the spelling.- #- # `Spree.admin_user_class` and the bare `Object` of a principal- # parameter never reach here: those parameters are stripped first.- #- # @return [String, nil]- def model_name_for(type)- return unless type.start_with?('Spree::')-- constant = type.safe_constantize- return unless constant.is_a?(Class) && constant < ActiveRecord::Base-- constant.name- end-- # What an array holds, read from the documented type: `Array<Hash>` holds- # objects, and anything else is treated as strings — the common case for- # a list of names or codes.- def item_type_for(types)- inner = types.filter_map { |type| type[/\AArray<(.+)>\z/, 1] }.first-- PRIMITIVES[inner] || 'string'- end-- def json_type_for(types)- concrete = types.reject { |type| type == 'nil' }- # `Array<Hash>` and friends — the outer container is what JSON sees.- concrete = concrete.map { |type| type.split('<').first }- concrete.filter_map { |type| PRIMITIVES[type] }.first || 'string'- end-- # The YARD block above `perform`, parsed from the workflow's own source.- #- # Read from source rather than through the YARD gem: the gem is a- # development dependency, and this has to work in production, where the- # tool list is built on every request.- #- # @return [Hash{Symbol => Hash}]- def docs- @docs ||= self.class.parse_docs(workflow_class)- end-- class << self- # Every keyword that names who acted, so none is ever offered to a- # caller as a free parameter.- #- # Read from {Spree::ActedBy} rather than listed here: the macro already- # records each actor association per model, exactly so a caller- # sweeping them walks all of them without being handed a list. A model- # that gains an actor gains it here in the same commit, and a name- # nobody declares cannot linger.- #- # @return [Array<Symbol>]- def principal_parameter_names- declared = if defined?(Spree::ActedBy)- Spree::ActedBy.models.flat_map(&:acted_by_associations).map(&:to_sym)- else- []- end-- (declared | UNCONVERTED_PRINCIPAL_PARAMETERS).uniq- end-- # Parsed once per workflow class and cached, because a tool list is- # built for every MCP request and the source never changes at runtime.- #- # @param workflow_class [Class]- # @return [Hash{Symbol => Hash}] `{types: [String], description: String}`- def parse_docs(workflow_class)- file, = workflow_class.instance_method(:perform).source_location- key = [workflow_class.name, file, (File.mtime(file) if file && File.exist?(file))]-- cache[key] ||= parse_source(workflow_class)- end-- # @return [void]- def clear_cache!- @cache = {}- end-- private-- def cache- @cache ||= {}- end-- def parse_source(workflow_class)- source = comment_above_perform(workflow_class)- return {} if source.blank?-- parse_param_tags(source)- end-- # The comment block immediately above `def perform`, joined so a- # `@param` whose prose wraps onto the next line keeps it.- def comment_above_perform(workflow_class)- location = workflow_class.instance_method(:perform).source_location- return if location.nil?-- file, line = location- return unless File.exist?(file)-- lines = File.readlines(file)- comment = []- index = line - 2- while index >= 0 && lines[index].strip.start_with?('#')- comment.unshift(lines[index].strip.delete_prefix('#').strip)- index -= 1- end- comment- end-- def parse_param_tags(comment_lines)- tags = {}- current = nil-- comment_lines.each do |line|- if (match = line.match(/\A@param\s+(\w+)\s+\[([^\]]*)\]\s*(.*)\z/))- current = match[1].to_sym- tags[current] = {- types: match[2].split(',').map(&:strip).reject(&:empty?),- description: match[3].strip- }- elsif line.start_with?('@')- current = nil- elsif current && line.present?- tags[current][:description] = [tags[current][:description], line].reject(&:blank?).join(' ')- end- end-- tags- end- end- end- end-enddiff --git a/spree/core/lib/spree/agent_tools/workflow_tool.rb b/spree/core/lib/spree/agent_tools/workflow_tool.rbdeleted file mode 100644index adbcd436d2..0000000000--- a/spree/core/lib/spree/agent_tools/workflow_tool.rb+++ /dev/null@@ -1,654 +0,0 @@-module Spree- module AgentTools- # One agent tool per exposed workflow.- #- # Every back-office write already goes through a workflow, so there is- # nothing to hand-write: the allowlist names a `Spree::Dependencies` key- # and a permission, {WorkflowSchema} reads the argument contract off the- # workflow's own `perform`, and this class resolves the arguments, injects- # the principal, takes the lock the controller takes and shapes the result.- #- # Generated classes are anonymous subclasses cached per dependency key, so- # a host app that swaps `Spree.order_cancel_workflow` for its own class- # keeps the tool and gets the replacement's schema.- class WorkflowTool < Spree::AgentTool- class_attribute :dependency_key, instance_accessor: false- class_attribute :schema_except, instance_accessor: false, default: [].freeze- class_attribute :summary_override, instance_accessor: false-- class << self- # Builds (and caches) the tool class for one exposed workflow.- #- # @param dependency_key [Symbol] a `Spree::Dependencies` key- # @param permission [String] the `write_*` key gating it- # @param except [Array<Symbol>] parameters to hide- # @param summary [#call, nil] overrides the generated confirmation line- # @return [Class<WorkflowTool>, nil] nil when the key does not resolve- def for(dependency_key, permission:, except: [], summary: nil)- workflow_class = resolve_workflow(dependency_key)- return if workflow_class.nil?-- # Keyed by what actually shapes the class, including the workflow's- # own source location and mtime: a tool's parameters are read off- # `perform`, so editing a workflow in development has to produce a- # new tool rather than serve the schema built before the reload.- # That is the same reason the registry stores names and not classes.- #- # A summary override is a callable with no stable identity, so its- # presence is part of the key but the object is not — otherwise- # every reload would leave a permanent entry behind.- cache_key = [dependency_key, workflow_class.name, source_fingerprint(workflow_class),- permission, except, !summary.nil?]- cached = cache[cache_key]- return cached if cached && cached.summary_override.equal?(summary)-- cache[cache_key] = build(dependency_key, workflow_class, permission, except, summary)- end-- # @return [void]- def clear_cache!- @cache = {}- end-- # Identifies the source a tool's schema was read from, so an edit in- # development invalidates the generated class. Nil in a packaged gem- # whose source is not on disk, which simply means the key never- # changes there — correct, since the source cannot change either.- #- # @return [Array, nil]- def source_fingerprint(workflow_class)- file, = workflow_class.instance_method(:perform).source_location- return if file.nil?-- [file, File.mtime(file)]- rescue StandardError- nil- end-- # The tool name for a dependency key: the workflow's dotted identity- # with dots as underscores, because MCP names allow only letters,- # digits, underscore and hyphen.- #- # @param workflow_class [Class]- # @return [String]- def tool_name_for(workflow_class)- workflow_class.workflow_key.tr('.', '_')- end-- # @return [Class, nil]- def resolve_workflow(dependency_key)- Spree.public_send(dependency_key)- rescue NoMethodError, NameError- nil- end-- # The workflow's own leading comment, first paragraph — what the class- # says it does, in the author's words rather than a second description- # kept in step by hand.- #- # @param workflow_class [Class]- # @return [String]- def description_for(workflow_class)- paragraph = leading_comment(workflow_class)- return "Runs the #{workflow_class.workflow_key.tr('.', ' ')} workflow." if paragraph.blank?-- paragraph- end-- private-- def cache- @cache ||= {}- end-- def build(dependency_key, workflow_class, permission_key, except, summary)- derived_schema = WorkflowSchema.new(workflow_class, except: except)- derived_name = tool_name_for(workflow_class)- derived_description = description_for(workflow_class)-- Class.new(self) do- self.dependency_key = dependency_key- self.schema_except = except.freeze- self.summary_override = summary-- tool_name derived_name- description derived_description- permission permission_key- mutating!-- derived_schema.parameters.each do |parameter|- param parameter[:name],- type: parameter[:json_type].to_sym,- items: parameter[:item_type]&.to_sym,- description: parameter[:description],- required: parameter[:required]- end- end- end-- def leading_comment(workflow_class)- location = Object.const_source_location(workflow_class.name)- return if location.nil?-- file, line = location- return unless file && File.exist?(file)-- lines = File.readlines(file)- comment = []- index = line - 2- while index >= 0 && lines[index].strip.start_with?('#')- comment.unshift(lines[index].strip.delete_prefix('#').strip)- index -= 1- end- # First paragraph only — the rest is design rationale for readers of- # the class, not for a model choosing between tools.- comment.take_while(&:present?).join(' ').presence- end- end-- # @return [Class] the workflow this tool runs, resolved now so a host- # app's replacement is picked up without a restart- def workflow_class- self.class.resolve_workflow(self.class.dependency_key)- end-- # @return [WorkflowSchema]- def schema- @schema ||= WorkflowSchema.new(workflow_class, except: self.class.schema_except)- end-- # Runs the workflow with the caller's arguments.- #- # Model-typed arguments arrive as prefixed ids and are resolved through- # the resource map under the context's store, so another store's id is- # simply not found. Principal parameters are never accepted from the- # caller — they are filled from the authenticated principal.- #- # @return [Hash] the result handed back to the model- def call(**arguments)- resolved = resolve_arguments(arguments)- return resolved if resolved.is_a?(Hash) && resolved[:error]-- # The endpoint runs this workflow behind its own routing,- # authentication, authorization and serializer, so when there is one- # the request goes through it rather than beside it.- return dispatch(resolved) if endpoint-- refusal = unauthorized_create || unauthorized_record(resolved)- return refusal if refusal-- keywords = resolved.merge(principal_arguments).merge(context_arguments)-- run(keywords, subject: subject_record(resolved))- rescue ArgumentError => e- { error: e.message }- end-- # @return [Spree::AgentTools::WorkflowEndpoints::Entry, nil]- def endpoint- return @endpoint if defined?(@endpoint)-- @endpoint = WorkflowEndpoints.find(self.class.dependency_key)- end-- # One line saying what this tool did, for the client's confirmation- # prompt and the assistant's approval card.- #- # @param arguments [Hash]- # @return [String]- def summary(arguments, subject: nil)- return self.class.summary_override.call(context, arguments) if self.class.summary_override-- action = workflow_class.workflow_key.tr('.', ' ').humanize- subject ||= subject_record(arguments)- [action, label_for(subject)].compact.join(' ')- end-- private-- # Runs the workflow by calling the operation that runs it.- #- # The path's `:id` is the record the write is about; a parent segment- # (`:order_id` on a payment) is read from that record rather than asked- # for, since the caller named the payment and the order follows from it.- # Everything else travels in the body under the name the endpoint- # documents, which is not always the workflow's keyword — a- # cancellation's `note:` is `cancel_note` on the wire.- def dispatch(resolved)- subject = subject_record(resolved)- path, missing = endpoint_path(subject, resolved)- return { error: missing } if missing-- response = ApiDispatch.new(context).call(- method: endpoint.verb.downcase.to_sym, path: path, body: dispatch_body(resolved)- )- return { error: response.error_message } unless response.success?-- { summary: summary(resolved, subject: subject),- record: payload_summary(response.data) }.compact- end-- def endpoint_path(subject, resolved)- values = {}-- endpoint.path_params.each do |segment|- record = segment == 'id' ? subject : parent_for(segment, subject, resolved)- return [nil, "This tool needs a #{segment.sub(/_id\z/, '').humanize.downcase} it was not given."] if- record.nil?-- values[segment] = record.prefixed_id- end-- [endpoint.path_for(values), nil]- end-- # A parent segment names an association: `:order_id` on a payment is- # `payment.order`. A record the caller named for that association is- # preferred, so a split payment is refunded against the order the- # caller meant.- def parent_for(segment, subject, resolved)- name = segment.sub(/_id\z/, '')- named = resolved[name.to_sym]- return named if named.is_a?(ActiveRecord::Base)-- from_subject = subject.try(name)- return from_subject if from_subject-- # A keyword whose name does not match the segment but whose record is- # what the segment addresses: a label's `owner:` is the fulfillment in- # `/fulfillments/:fulfillment_id`, and the same tool reaches a return- # through `/returns/:return_id`.- records(resolved).find { |record| record.class.name.demodulize.underscore == name }- end-- # What the operation accepts, under its own names. A record resolved for- # a path segment is already in the path; anything else the endpoint does- # not document is left out rather than sent and ignored.- def dispatch_body(resolved)- accepted = endpoint.body_keys- return {} if accepted.empty?-- resolved.each_with_object({}) do |(name, value), body|- # An `attributes` hash is not a field of the body — it IS the body.- # The endpoint documents its keys one by one, so it merges in- # rather than travelling under a name of its own.- if name.to_s == 'attributes' && value.is_a?(Hash)- body.merge!(value.transform_keys(&:to_s))- next- end-- key = body_key_for(name, accepted)- next if key.nil?-- body[key] = value.is_a?(ActiveRecord::Base) ? value.prefixed_id : value- end- end-- # The endpoint's name for a workflow keyword.- #- # Exact first, then the `_id` form a record takes on the wire. Failing- # both, the one accepted key that ENDS in the keyword: a cancellation's- # `reason:` is `cancel_reason_id` and its `note:` is `cancel_note`,- # qualified by the action rather than the resource. Matched on the- # suffix rather than by guessing the qualifier, and only when exactly- # one key matches — two would make the choice a coin toss, and a- # silently misplaced value is worse than a refusal.- def body_key_for(name, accepted)- exact = [name.to_s, "#{name}_id"].find { |candidate| accepted.include?(candidate) }- return exact if exact-- suffixed = accepted.select { |key| key.end_with?("_#{name}", "_#{name}_id") }- suffixed.first if suffixed.one?- end-- # A record as the endpoint returned it, summarised the way a record read- # from the map would be.- def payload_summary(data)- return unless data.is_a?(Hash)-- entry = ResourceMap.all.find { |candidate| candidate.key == data['object'] } ||- subject_entry- return { id: data['id'] } if entry.nil?-- RecordSummary.from_payload(entry: entry, payload: data)- end-- # Holding `write_orders` says an admin may change orders; it does not say- # they may change *this* one. A host app narrows that with a- # record-level rule, the Admin API honours it, and a workflow tool must- # too — otherwise an agent writes records its user could not touch by- # clicking. Every record the workflow was handed is checked, not just the- # subject, since a cancellation reason from another seller is as much a- # leak as the order itself.- def unauthorized_record(arguments)- # A create's own action is checked against the class above; the records- # it was handed are collaborators (a supplier, a stock location), so- # they are checked for the read-and-use they actually get.- action = ability_action == :create ? :show : ability_action-- records(arguments).each do |record|- refusal = unauthorized(action, record)- return refusal if refusal- end-- nil- end-- # A create workflow has no record to check yet — the workflow builds it- # — so the Admin API's `authorize_resource!(@resource, :create)` has no- # counterpart here. Authorize against the class instead, which is what a- # record-level rule on a create would be evaluated against anyway.- #- # @return [Hash, nil]- def unauthorized_create- return unless ability_action == :create-- # A key whose model does not resolve leaves nothing to authorize- # against, and `can?(:create, nil)` answers true — so the check would- # pass for exactly the workflow nobody can vouch for. The attribute- # filter is keyed off the same lookup and would also fall open, which- # is the tenancy hole it exists to close.- model = created_model- return { error: 'This tool cannot be used: its workflow names a resource that does not exist.' } if model.nil?- return if context.can?(:create, model)-- { error: "You do not have permission to create this #{model.model_name.human.downcase}." }- end-- # What the workflow creates, named by its own key: `products.create`- # creates a product. A key whose model cannot be resolved falls back to- # the subject check alone rather than guessing.- #- # @return [Class, nil]- def created_model- @created_model ||= "Spree::#{workflow_class.workflow_key.split('.').first.classify}".safe_constantize- end-- # Which CanCanCan action this workflow amounts to. The stock catalog- # grants writes as `:manage`, which covers everything — but an ability- # may be replaced, and a host app that grants `:update` without- # `:destroy` means it: a deletion checked as an update would go through.- #- # @return [Symbol]- def ability_action- case workflow_class.workflow_key.split('.').last- when 'destroy' then :destroy- when 'create' then :create- else :update- end- end-- # Only what the caller named. The store and the principal are injected- # from the credential, so checking them would ask whether the caller may- # "update" their own store or their own user — which an order-desk role- # legitimately may not, and which has nothing to do with the write they- # actually asked for.- def records(arguments)- arguments.values.select { |value| value.is_a?(ActiveRecord::Base) }- end-- # The record the write is about, for the lock and the confirmation line.- def subject_record(arguments)- records(arguments).first- end-- def run(keywords, subject: nil)- result = with_subject_lock(subject) { workflow_class.call(**keywords) }-- if result.success?- { summary: summary(keywords, subject: result.value.is_a?(ActiveRecord::Base) ? result.value : subject),- record: record_result(result.value) }- else- { error: error_text(result) }- end- end-- # The same row lock the admin controllers take for an order-subject- # workflow. Taken generically: whichever record the workflow is acting- # on is the one that must not change underneath it.- def with_subject_lock(subject, &)- return yield unless subject.respond_to?(:with_lock) && subject.persisted?-- subject.with_lock(&)- end-- def record_result(value)- return unless value.is_a?(ActiveRecord::Base)-- entry = ResourceMap.all.find { |candidate| value.is_a?(candidate.model_class) }- return { id: value.try(:prefixed_id) } if entry.nil?-- RecordSummary.call(entry: entry, record: value)- end-- # The workflow's own refusal, in its own words, so the model can correct- # itself instead of retrying blind.- def error_text(result)- error = result.error- errors = error.respond_to?(:value) ? error.value : error-- return errors.full_messages.to_sentence if errors.respond_to?(:full_messages) && errors.any?- return error.to_s if error.present?-- 'The workflow refused the change.'- end-- # Who acted, for the workflow keywords that record it.- #- # Only where the record can actually hold this principal. Several- # models still declare `created_by` / `reviewed_by` as a plain- # `belongs_to` on the admin-user class rather than through `acted_by`,- # and handing those an API key raises AssociationTypeMismatch deep- # inside the workflow — a protocol-level failure where the honest- # outcome is simply an unattributed record.- def principal_arguments- principal = context.principal- schema.principal_parameters.- select { |name| principal_storable?(name, principal) }.- index_with { principal }- end-- # @return [Boolean]- def principal_storable?(name, principal)- association = subject_model&.reflect_on_association(name)- return true if association.nil? || association.polymorphic?-- expected = association.klass- principal.is_a?(expected)- rescue NameError- true- end-- # The model this workflow writes, for checking what its associations- # will accept. Nil when the key names nothing resolvable.- def subject_model- return @subject_model if defined?(@subject_model)-- @subject_model = created_model- rescue StandardError- @subject_model = nil- end-- # Tenancy comes from the credential, never from a parameter.- def context_arguments- schema.context_parameters.index_with { context.store }- end-- # Turns the caller's JSON arguments into what `perform` expects,- # resolving every model-typed parameter from its prefixed id.- #- # @return [Hash, Hash{Symbol => String}] keywords, or an `{error:}` result- def resolve_arguments(arguments)- resolved = {}-- schema.parameters.each do |parameter|- name = parameter[:name]- next unless arguments.key?(name)-- value = arguments[name]- next if value.nil?-- if parameter[:model_name]- record = find_record(parameter[:model_name], value)- return { error: "No #{parameter[:model_name].demodulize.underscore.humanize.downcase} found for #{name} #{value.inspect}." } if record.nil?-- resolved[name] = record- elsif parameter[:item_type] == 'object'- rows, refusal = resolve_rows(name, value)- return refusal if refusal-- resolved[name] = rows- elsif parameter[:json_type] == 'object'- filtered, refusal = permitted_attributes(value)- return refusal if refusal-- resolved[name] = filtered- else- resolved[name] = value- end- end-- resolved- end-- # Only the attributes the Admin API itself would accept for the record- # this workflow writes.- #- # A workflow is an internal service that has always trusted its caller,- # so it assigns the hash it is handed. The REST controllers filter first- # — `permitted_params` is a fixed list that never includes a tenancy- # key — and a tool must do the same before a workflow sees the payload.- # Without it a caller naming `store_id` writes into another merchant's- # store, since the workflow assigns the hash after setting tenancy.- #- # Unknown keys are named back rather than dropped, matching- # `ResourceWrite` so a model that guessed a field learns the real one.- #- # @return [Array(Hash, nil), Array(nil, Hash)]- def permitted_attributes(attributes)- return [attributes, nil] unless attributes.is_a?(Hash)-- entry = subject_entry- if entry.nil?- # No entry means no list of what the Admin API would accept, and- # forwarding the hash unchecked is what let a caller name- # `store_id` and write into another merchant's store.- return [nil, { error: 'This tool cannot be used: its resource is not one an agent may write.' }]- end-- attributes = attributes.transform_keys(&:to_s)- allowed = entry.writable_attribute_names- return [attributes, nil] if allowed.blank?-- rejected = attributes.keys - allowed- return [attributes, nil] if rejected.empty?-- [nil, { error: "#{entry.key} does not accept #{rejected.to_sentence}. " \- "Accepted attributes: #{allowed.to_sentence}." }]- end-- # The map entry for what this workflow writes, which owns the list of- # attributes the Admin API accepts for it.- #- # @return [ResourceMap::Entry, nil]- def subject_entry- return @subject_entry if defined?(@subject_entry)-- model = created_model || subject_model- @subject_entry = model && ResourceMap.all.find { |candidate| candidate.model_name == model.name }- rescue StandardError- @subject_entry = nil- end-- # A list of hashes — a purchase order's or stock transfer's `items:` —- # names records by prefixed id inside each row, and the workflow builds- # associations from them. Without resolving those the association is- # handed a string and the record fails validation with "must exist",- # which reads to the model as a bad id rather than a missing step.- #- # @return [Array(Array<Hash>, nil), Array(nil, Hash)]- def resolve_rows(name, value)- rows = Array(value).map do |row|- next row unless row.is_a?(Hash)-- resolved_row = {}- row.each do |field, field_value|- model_name = nested_model_name(field)-- if model_name && field_value.is_a?(String)- record = find_record(model_name, field_value)- if record.nil?- return [nil, { error: "No #{field} found for #{field_value.inspect} in #{name}." }]- end-- resolved_row[field.to_sym] = record- else- resolved_row[field.to_sym] = field_value- end- end- resolved_row- end-- [rows, nil]- end-- # Which model a row's field names, taken from the resource map so only- # something the caller may already read can be referenced.- #- # @return [String, nil]- def nested_model_name(field)- entry = Spree::AgentTools::ResourceMap.find(field.to_s.pluralize)- return unless entry- return unless context.permitted?(entry.permission)-- entry.model_class.name- end-- # Resolves a prefixed id within the caller's store, through the resource- # map — so tenancy is answered the same way every read is.- #- # A model the map does not hold is one with no store scoping of its own- # (a certificate belongs to a company, a submission to a seller). Those- # resolve through the mapped parent, so the id still has to belong to- # this store; a model with neither is not resolvable and the caller is- # told so rather than being handed another store's record.- def find_record(model_name, value)- relation = store_scoped_relation(model_name)- return if relation.nil?-- relation.find_by_prefix_id(value)- rescue StandardError- nil- end-- def store_scoped_relation(model_name)- entry = ResourceMap.all.find { |candidate| candidate.model_name == model_name }- return entry.scope_for(context) if entry-- parent_scoped_relation(model_name.constantize)- end-- # Narrows an unscoped model through whichever of its parents the map- # knows, so `certificate` is looked up among this store's companies'- # certificates rather than every store's.- def parent_scoped_relation(model_class)- model_class.reflect_on_all_associations(:belongs_to).each do |association|- next if association.polymorphic?-- entry = ResourceMap.all.find { |candidate| candidate.model_name == association.klass.name }- next if entry.nil?-- return model_class.where(association.foreign_key => entry.scope_for(context).select(:id))- end-- nil- end-- def label_for(record)- return if record.nil?-- record.try(:number) || record.try(:name) || record.try(:prefixed_id)- end- end- end-enddiff --git a/spree/mcp/lib/spree/mcp/server.rb b/spree/mcp/lib/spree/mcp/server.rbindex 574c7fe632..5c51233a29 100644--- a/spree/mcp/lib/spree/mcp/server.rb+++ b/spree/mcp/lib/spree/mcp/server.rb@@ -9,6 +9,22 @@ module Spree# request) is not what mounts this. An ordinary admin API controller does,# and hands the JSON-RPC message to {MCP::Server#handle_json}.module Server+ # The protocol server, plus the 6.0.0 tool names kept callable through+ # 6.0.x. They answer `tools/call` but are not in `tools/list`: a client+ # that learned one keeps working, and a new one is shown only the+ # current names. The gem lists `@tools` and looks a call up through+ # `#tools`, so an unknown name is resolved there, only when called.+ class AdminServer < ::MCP::Server+ # @param resolver [#call] name => MCP tool class, or nil+ attr_writer :resolver++ def tools+ resolver = @resolver+ lookup = Hash.new { |_tools, name| resolver&.call(name) }+ lookup.merge!(super)+ end+ end+# What the model is told about using this server at discovery, so it# reaches for the discovery tools before guessing at names and filters.INSTRUCTIONS = <<~TEXT.freeze@@ -47,7 +63,7 @@ module Spree# @param context [Spree::AgentTools::Context] who is asking, and where# @return [MCP::Server]def for(context)- server = ::MCP::Server.new(+ server = AdminServer.new(name: 'spree-admin',title: "#{context.store.name} (Spree admin)",version: Spree.version,@@ -56,6 +72,10 @@ module Spreeserver_context: { store_id: context.store.id })+ server.resolver = lambda do |name|+ tool = Spree.admin_agent_tools.find_for(name, context)+ ToolAdapter.build(tool) if tool+ endregister_resources(server, context)serverenddiff --git a/spree/mcp/lib/spree/mcp/tool_adapter.rb b/spree/mcp/lib/spree/mcp/tool_adapter.rbindex 0ca43188a0..5ecc5a3c23 100644--- a/spree/mcp/lib/spree/mcp/tool_adapter.rb+++ b/spree/mcp/lib/spree/mcp/tool_adapter.rb@@ -24,26 +24,17 @@ module Spree) { |**arguments| adapter.respond(tool, arguments) }end- # The tool's declared params as JSON Schema.+ # The tool's arguments as the gem's schema object, built once per tool+ # class. Building one deep-copies and validates the schema, and an+ # action tool's schema is a whole request body: done on every request+ # for every tool, it was most of what answering `tools/list` cost.+ # Keyed weakly by the tool class, so a class replaced on a code reload+ # is let go with its schema.## @param tool [Spree::AgentTool]- # @return [Hash]+ # @return [MCP::Tool::InputSchema]def input_schema(tool)- properties = tool.params.to_h do |name, options|- property = { type: json_type(options[:type]) }- property[:description] = options[:description] if options[:description].present?- # An array must say what it holds: a client validating arguments- # against the schema refuses the call otherwise.- property[:items] = { type: json_type(options[:items] || :string) } if property[:type] == 'array'-- [name.to_s, property]- end-- {- type: 'object',- properties: properties,- required: tool.params.select { |_name, options| options[:required] }.keys.map(&:to_s)- }+ schemas[tool.class] ||= ::MCP::Tool::InputSchema.new(tool.class.input_schema)end# Clients that gate confirmation on annotations rather than on a@@ -88,17 +79,8 @@ module Spreeprivate- # A tool declares Ruby-ish types; JSON Schema wants its own names, and- # anything unrecognised is a string, which every client can render.- def json_type(type)- case type&.to_sym- when :boolean then 'boolean'- when :integer then 'integer'- when :number, :float, :decimal then 'number'- when :object, :hash then 'object'- when :array then 'array'- else 'string'- end+ def schemas+ @schemas ||= ObjectSpace::WeakKeyMap.newend# A line the client can show beside its confirmation prompt, and thediff --git a/spree/mcp/spec/lib/spree/mcp/server_spec.rb b/spree/mcp/spec/lib/spree/mcp/server_spec.rbindex 7b6f403a75..3cb56409b9 100644--- a/spree/mcp/spec/lib/spree/mcp/server_spec.rb+++ b/spree/mcp/spec/lib/spree/mcp/server_spec.rb@@ -94,20 +94,17 @@ RSpec.describe Spree::Mcp::Server doexpect(cancel.dig('annotations', 'readOnlyHint')).to be(false)end- it 'derives each workflow tool\'s schema from the workflow itself' do+ it 'builds each action tool\'s schema from its Admin API operation' docancel = tools.find { |tool| tool['name'] == 'orders_cancel' }properties = cancel.dig('inputSchema', 'properties')- expect(properties).to include('order', 'refund_payments', 'note')- expect(cancel.dig('inputSchema', 'required')).to eq(['order'])+ expect(properties).to include('id', 'refund_payments', 'cancel_note')endit 'never offers the principal or the store as a parameter' do- cancel = tools.find { |tool| tool['name'] == 'orders_cancel' }- create = tools.find { |tool| tool['name'] == 'variants_create' }+ offered = tools.flat_map { |tool| tool.dig('inputSchema', 'properties').to_h.keys }- expect(cancel.dig('inputSchema', 'properties')).not_to have_key('canceler')- expect(create.dig('inputSchema', 'properties')).not_to have_key('store')+ expect(offered).not_to include('canceler', 'store', 'store_id')endit 'hides a deprecated parameter the allowlist excludes' dodiff --git a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rbindex 55732a1d07..d9a68f3404 100644--- a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb+++ b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb@@ -362,13 +362,31 @@ RSpec.describe 'Admin MCP endpoint', type: :request doexpect(order.canceler).to eq(admin)end- it 'carries the workflow\'s own refusal back as a tool error' do+ # Through 6.0.x a client that learned a 6.0.0 name keeps working, while+ # a new listing shows only the current ones.+ it 'still answers a 6.0.0 tool name it no longer lists' do+ product = create(:product, store: store)+ sku = "SKU-#{SecureRandom.hex(3)}"++ listed = post_rpc('tools/list', headers: { 'Authorization' => "Bearer #{token}" }).+ dig('result', 'tools').map { |tool| tool['name'] }+ body = post_rpc('tools/call',+ { name: 'variants_create',+ arguments: { 'product' => product.prefixed_id, 'attributes' => { 'sku' => sku } } },+ headers: { 'Authorization' => "Bearer #{token}" })++ expect(listed).not_to include('variants_create')+ expect(body.dig('result', 'isError')).to be(false)+ expect(Spree::Variant.where(sku: sku)).to exist+ end++ it 'carries the endpoint\'s own refusal back as a tool error' dobody = post_rpc('tools/call',{ name: 'orders_cancel', arguments: { 'order' => 'order_nope' } },headers: { 'Authorization' => "Bearer #{token}" })expect(body.dig('result', 'isError')).to be(true)- expect(body.dig('result', 'content').first['text']).to include('order')+ expect(body.dig('result', 'content').first['text']).to include('Order not found')endend