solidus_mcp 0.2.0.rc2 → 0.2.0.rc3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +63 -0
  3. data/README.md +321 -3
  4. data/app/assets/stylesheets/solidus_mcp/admin.css +39 -0
  5. data/app/assets/stylesheets/solidus_mcp/consent.css +77 -0
  6. data/app/controllers/solidus_admin/mcp_activity_controller.rb +67 -0
  7. data/app/controllers/solidus_mcp/endpoint_controller.rb +36 -0
  8. data/app/models/solidus_mcp/activity_event.rb +37 -0
  9. data/app/models/solidus_mcp/audit_context.rb +7 -0
  10. data/app/models/solidus_mcp/stock_adjustment.rb +16 -0
  11. data/app/models/solidus_mcp/tool_request.rb +10 -0
  12. data/app/services/solidus_mcp/action_audit.rb +169 -0
  13. data/app/services/solidus_mcp/image_context.rb +44 -0
  14. data/app/services/solidus_mcp/order_workflow_authorization.rb +76 -0
  15. data/app/services/solidus_mcp/tool_request_execution.rb +76 -0
  16. data/app/tools/solidus_mcp/tools/add_product_option_type.rb +36 -0
  17. data/app/tools/solidus_mcp/tools/add_product_to_taxon.rb +40 -0
  18. data/app/tools/solidus_mcp/tools/adjust_stock.rb +98 -0
  19. data/app/tools/solidus_mcp/tools/attach_product_image.rb +77 -0
  20. data/app/tools/solidus_mcp/tools/bulk_update_variant_prices.rb +1 -1
  21. data/app/tools/solidus_mcp/tools/cancel_order.rb +44 -0
  22. data/app/tools/solidus_mcp/tools/create_product.rb +1 -0
  23. data/app/tools/solidus_mcp/tools/create_variant_price.rb +59 -0
  24. data/app/tools/solidus_mcp/tools/list_option_types.rb +34 -0
  25. data/app/tools/solidus_mcp/tools/list_option_values.rb +27 -0
  26. data/app/tools/solidus_mcp/tools/list_product_images.rb +26 -0
  27. data/app/tools/solidus_mcp/tools/list_shipping_categories.rb +24 -0
  28. data/app/tools/solidus_mcp/tools/list_stock_locations.rb +27 -0
  29. data/app/tools/solidus_mcp/tools/list_taxons.rb +40 -0
  30. data/app/tools/solidus_mcp/tools/publish_product.rb +32 -0
  31. data/app/tools/solidus_mcp/tools/refund_payment.rb +63 -0
  32. data/app/tools/solidus_mcp/tools/remove_product_image.rb +33 -0
  33. data/app/tools/solidus_mcp/tools/reorder_product_images.rb +41 -0
  34. data/app/tools/solidus_mcp/tools/ship_shipment.rb +63 -0
  35. data/app/tools/solidus_mcp/tools/unpublish_product.rb +29 -0
  36. data/app/tools/solidus_mcp/tools/update_variant.rb +54 -0
  37. data/app/tools/solidus_mcp/tools/update_variant_price.rb +1 -1
  38. data/app/views/solidus_admin/mcp_activity/index.html.erb +53 -0
  39. data/app/views/solidus_admin/mcp_connections/index.html.erb +2 -0
  40. data/app/views/solidus_mcp/authorizations/new.html.erb +59 -41
  41. data/config/routes.rb +1 -0
  42. data/db/migrate/20261112000000_create_solidus_mcp_stock_adjustments.rb +19 -0
  43. data/db/migrate/20261112010000_create_solidus_mcp_tool_requests.rb +19 -0
  44. data/db/migrate/20261112020000_create_solidus_mcp_activity_events.rb +34 -0
  45. data/db/migrate/20261112020100_add_actor_role_to_mcp_activity_events.rb +7 -0
  46. data/lib/solidus_mcp/audited_server.rb +25 -0
  47. data/lib/solidus_mcp/engine.rb +8 -3
  48. data/lib/solidus_mcp/policy.rb +4 -4
  49. data/lib/solidus_mcp/registry.rb +5 -2
  50. data/lib/solidus_mcp/server.rb +1 -2
  51. data/lib/solidus_mcp/tool.rb +9 -7
  52. data/lib/solidus_mcp/version.rb +1 -1
  53. data/lib/solidus_mcp.rb +5 -1
  54. metadata +37 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f5922154aa4d65341aecb0312e8a1a72d20ef1e81a5e423f000eaa6f6239e4fd
4
- data.tar.gz: 2ff83f035e9b9268c9df907b4f40004b1b3528af8c30ff033b8b3fe4493847b2
3
+ metadata.gz: 0daf16ddf5123c0b832d157a22ae16cb6e3fa9ad0895863cfec168d60ed684ef
4
+ data.tar.gz: 2292dfbecdbaac0c3f507bd6c38521ec41f185fee3905d2ddabeda14c9a60dca
5
5
  SHA512:
6
- metadata.gz: fd23eee0805800c0de1d3a939c1ea99358aef8ad711b3437f4c002c17a67b5da3388dd0fa37dfc7fa0bb48ceb0cf10b588e7b8e3e8f92db836f13ada990141ba
7
- data.tar.gz: a8aba2d7d878b8993289046e915eba690d8dd70a7fd1fc9fe241337174bfd12b741fbcc305658b809cceab09002179533b8fc43f43fbb4f2bbc8765cd1eae4a5
6
+ metadata.gz: 562671c81c943db87070308ddb24b09b4cda0e38c41ffd826817619b9eddd696d40b24fe24b04551a00e0c5867dc91118243b59e44ab4dd700c3542f9ba4a7cd
7
+ data.tar.gz: eef9e1db283058b7ed952dfb1b75c730952812333d18fe0b501f24b46700de1595b0d992039ed67d2db610939b4c494e6a1ae47932752042ab5f0fcea818690b
data/CHANGELOG.md CHANGED
@@ -2,6 +2,69 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.2.0.rc3 (2026-11-12)
6
+
7
+ - Add centralized MCP activity auditing for tool calls and protocol actions,
8
+ including denied attempts, schema errors, partial batches, custom tools and
9
+ direct Ruby execution. Retain actor/client attribution, safe target/result IDs,
10
+ declared changed-field names, outcomes and timing without copying raw inputs,
11
+ responses, credentials or exception messages. Require a saved initial event
12
+ before execution and preserve unfinished evidence on interruption.
13
+ - Add a read-only **AI connections → MCP activity** browser with action grouping,
14
+ user/tool/outcome/time filters and cursor pagination. Enforce the existing MCP
15
+ hierarchy and retain historical role snapshots to protect privileged activity.
16
+ Add optional custom-tool `audit_action` metadata. Run engine migrations before
17
+ serving MCP after upgrading.
18
+
19
+ - Complete the pending standard tool catalog with separate tool and spec files:
20
+ image listing, bounded base64 upload, complete reordering and removal; product
21
+ publication/withdrawal; price-context creation; order cancellation, shipment
22
+ fulfillment, and payment refunds. Preserve Solidus validations and workflows,
23
+ parent/record and attribute permissions, ordering, and least-privilege grants.
24
+ - Add durable tool request records for image retries and external operations.
25
+ Commit gateway/fulfillment claims before effects; retain uncertain outcomes and
26
+ block further external operations on that order until trusted reconciliation.
27
+ Run `bin/rails solidus_mcp:migrate` after upgrading. Add ActiveStorage tables only
28
+ to the disposable test host and cover real attachment and carton workflows.
29
+
30
+ - Add `add_product_to_taxon` with a dedicated write grant, product/taxon and
31
+ classification authorization, and additive, repeat-safe category assignment.
32
+ Preserve existing classifications and append new products in Solidus's taxon
33
+ ordering while holding product and taxon locks.
34
+
35
+ - Add `list_taxons` with a dedicated read grant, scoped cursor pagination, literal
36
+ name search, taxonomy and direct-parent filters, and a roots-only null-parent
37
+ filter. Return bounded hierarchy metadata and authorize explicit filter records.
38
+
39
+ - Add `adjust_stock` with a dedicated write grant, record and stock-count
40
+ authorization, signed Solidus stock movements, reasons, and backorder handling.
41
+ Add durable connection-scoped request keys with a unique index and atomic
42
+ movement/result recording to prevent duplicate adjustments across retries and
43
+ concurrent calls. Run `bin/rails solidus_mcp:migrate` after upgrading, and retain
44
+ the request records to preserve duplicate-request protection.
45
+
46
+ - Add `update_variant` for SKU, dimensions, weight, cost price, and inventory
47
+ tracking, with a dedicated write grant, attribute-aware authorization before
48
+ and after assignment, decimal-string inputs, and validated atomic updates.
49
+ - Add scoped, paginated `list_stock_locations` with operational flags and a
50
+ dedicated read grant, omitting location addresses and contact details.
51
+
52
+ - Add `add_product_option_type` with a dedicated write grant, authorization for
53
+ both records and new associations, and additive, repeat-safe attachment under
54
+ a product lock. Preserve existing option positions and variants.
55
+
56
+ - Add paginated `list_option_types`, `list_option_values`, and
57
+ `list_shipping_categories` discovery tools with separate grants, scoped records,
58
+ parent authorization, and literal option-type name filtering.
59
+
60
+ - Style the OAuth consent page with the MCP admin palette and shared controls,
61
+ including responsive layout and keyboard focus indicators, without requiring
62
+ Solidus Admin or changing the authorization flow.
63
+
64
+ - Express nullable country inputs in pricing tool schemas with `anyOf` branches
65
+ for improved MCP client compatibility, preserving required fields and validation.
66
+ ## 0.2.0.rc2 (2026-11-08)
67
+
5
68
  - Add optional product and order serializer hooks for built-in read tools, with
6
69
  a plain Ruby interface and an Alba adapter example. Preserve record authorization,
7
70
  pagination, and tool-owned order line items; resolve class names across Rails reloads.
data/README.md CHANGED
@@ -29,7 +29,7 @@ These instructions assume you already have a working Solidus application. If you
29
29
  Add the gem to your `Gemfile`:
30
30
 
31
31
  ```ruby
32
- gem 'solidus_mcp', '0.2.0.rc1'
32
+ gem 'solidus_mcp', '0.2.0.rc3'
33
33
  ```
34
34
 
35
35
  Then run:
@@ -125,7 +125,7 @@ bin/rails db:migrate
125
125
  bin/rails solidus_mcp:migrate
126
126
  ```
127
127
 
128
- The first command runs your app's migrations, including the generated Doorkeeper migration. The second runs the gem's migrations directly from the installed gem. These add connection permissions and audits, OAuth resource and PKCE attributes, and MCP administrator assignments.
128
+ The first command runs your app's migrations, including the generated Doorkeeper migration. The second runs the gem's migrations directly from the installed gem. These add connection permissions and audits, OAuth resource and PKCE attributes, MCP administrator assignments, durable stock-adjustment request records, and tool request records for image uploads and external workflows.
129
129
 
130
130
  ### 7. Verify the endpoint
131
131
 
@@ -185,6 +185,57 @@ The hierarchy depends on your store's account security. Restrict who can change
185
185
 
186
186
  See [MCP administration hierarchy](docs/administration.md) for configuration details, audit behavior, and management APIs for stores without Solidus Admin.
187
187
 
188
+ ### MCP activity history
189
+
190
+ Open **AI connections → MCP activity** to review MCP actions. The history groups
191
+ read, create, update, and delete actions and filters by user email or ID, tool,
192
+ outcome, and a precise time range. Times without an explicit offset use the Rails
193
+ application time zone, which is displayed on the filters. Results use bounded
194
+ cursor pagination, with 50 events per page.
195
+
196
+ Every tool invocation is audited centrally, including custom tools and direct
197
+ Ruby `.execute` calls. SDK calls also record discovery and initialization, input
198
+ validation failures, and attempts to call unavailable tools. HTTP scope challenges,
199
+ disabled connections, and revoked known credentials are recorded even when they
200
+ are rejected before SDK dispatch. Requests with no identifiable credential remain
201
+ HTTP authentication failures; anonymous traffic is not written to this table.
202
+
203
+ Each event retains the user ID and MCP role at the time, OAuth application/client
204
+ and token IDs (not tokens), tool name and permission, action type, start/finish
205
+ times, duration, request/event IDs, outcome, and exception class. Safe numeric
206
+ input targets and returned record IDs are retained, including newly created
207
+ records. Requested update field names are recorded only when declared in the
208
+ tool's schema. Batch responses retain bounded record references and success flags,
209
+ so partial failures appear as **Partially succeeded**, not a successful whole batch.
210
+ Raw arguments, search text, values, response content, image data, credentials,
211
+ customer contact fields, and exception messages are not copied into the history.
212
+
213
+ MCP users see their own events. MCP administrators see their own events and
214
+ ordinary users' activity; other privileged users' history is hidden. Role snapshots
215
+ also protect historical privileged activity after an account is demoted or deleted.
216
+ Superadministrators see all activity, including attribution by ID after a user or
217
+ OAuth client is removed. The Admin history is read-only: it has no edit or delete
218
+ endpoints, and persisted model events reject normal edits/deletion. A started event
219
+ can be completed once through the recorder. Database administrators and trusted
220
+ application code still control the underlying database; this is not a tamper-proof
221
+ external audit archive.
222
+
223
+ The initial event must be saved before a tool runs. If that write fails, the tool
224
+ is not executed. Interrupted calls and completion-log failures remain
225
+ **Unfinished**, which can mean in progress or interrupted, not necessarily failed.
226
+ A completion-log failure is reported to the Rails logger without turning an
227
+ already-completed action into a failed response. The recorder does not wrap the
228
+ tool in a new transaction: ordinary tool transaction rollbacks preserve the event,
229
+ and gateway claim commits still work. If trusted Ruby callers enclose `.execute`
230
+ in their own transaction, audit rows participate in that enclosing transaction.
231
+
232
+ Run `bin/rails solidus_mcp:migrate` before using MCP after this upgrade. Keep the
233
+ activity tables available while serving MCP. Set a retention/archive policy in
234
+ trusted store maintenance code according to your volume and privacy requirements;
235
+ this extension does not automatically purge history. Invocation history records
236
+ who attempted or performed an MCP operation; it is separate from full model
237
+ versioning and before/after field diffs across every Solidus admin/API/CLI action.
238
+
188
239
  ## Integrating with existing Doorkeeper
189
240
 
190
241
  Reuse your existing OAuth tables and initializer. Do not call `SolidusMcp::Oauth.configure!` on top of an existing configuration: Doorkeeper is application-wide, and that helper is intended for a fresh installation.
@@ -209,26 +260,292 @@ Check your existing integrations before deploying changes to shared OAuth settin
209
260
  | Products | `search_products` | Search by product name or variant SKU. |
210
261
  | Products | `get_product` | Read product descriptions and supported attributes. |
211
262
  | Products | `get_product_variants` | List variants, including the master variant. |
263
+ | Products | `list_shipping_categories` | Discover shipping category IDs for product creation. |
264
+ | Products | `list_option_types` | Discover option types, optionally by name or product. |
265
+ | Products | `list_option_values` | Discover values for an authorized option type. |
266
+ | Products | `list_taxons` | Browse or search category IDs and hierarchy metadata. |
267
+ | Products | `add_product_to_taxon` | Add a category while preserving existing classifications and ordering. |
268
+ | Products | `list_product_images` | Read image metadata and display positions for a product or variant. |
269
+ | Products | `attach_product_image` | Upload a bounded base64 image with duplicate-request protection. |
270
+ | Products | `reorder_product_images` | Atomically set a parent's complete image order. |
271
+ | Products | `remove_product_image` | Permanently remove an image from its explicit parent. |
272
+ | Products | `publish_product` | Make a product available now, preserving discontinuation rules. |
273
+ | Products | `unpublish_product` | Withdraw availability while retaining variants and order history. |
274
+ | Products | `add_product_option_type` | Attach an existing option type without replacing other associations. |
212
275
  | Products | `create_product` | Create a draft product. |
213
276
  | Products | `update_product` | Update the name, description, and metadata fields. |
277
+ | Products | `update_variant` | Update SKU, weight, dimensions, cost price, or inventory tracking. |
278
+ | Pricing | `create_variant_price` | Create a price in an explicit currency/country context. |
214
279
  | Pricing | `get_variant_prices` | Read prices with their currency and country context. |
215
280
  | Pricing | `update_variant_price` | Update an existing price row. |
216
281
  | Pricing | `bulk_update_variant_prices` | Update up to 100 prices by SKU. |
282
+ | Inventory | `list_stock_locations` | Discover warehouse IDs, names, and operational flags. |
217
283
  | Inventory | `get_inventory_levels` | Read stock counts and backorderability by location. |
218
284
  | Inventory | `search_inventory` | Search stock levels by SKU or product name. |
285
+ | Inventory | `adjust_stock` | Apply a signed stock movement with a reason and duplicate-request protection. |
219
286
  | Orders | `search_orders` | Search by order number, state, or store ID. |
220
287
  | Orders | `get_order` | Read totals, status, and up to 100 authorized line items. |
221
288
  | Orders | `get_order_status` | Read order, payment, and shipment states. |
289
+ | Orders | `cancel_order` | Cancel a completed order through Solidus payment and inventory workflows. |
290
+ | Orders | `ship_shipment` | Fulfill one ready shipment with explicit tracking and notification choices. |
291
+ | Orders | `refund_payment` | Refund an explicit payment amount with durable retry protection. |
222
292
 
223
293
  Your client discovers each tool's input schema. Paginated tools accept `after_id` and `limit`, with a default limit of 25 and maximum of 100. Pass `next_after_id` from a response as the next request's `after_id` until it is null. Order results exclude customer contact information by default.
224
294
 
295
+ Use `list_shipping_categories` to find a `shipping_category_id`, or configure
296
+ `default_shipping_category_id` for product creation. Use `list_option_types`
297
+ with an optional `query` (case-insensitive literal name/presentation search) or
298
+ `product_id` to discover option types. Pass an `option_type_id` to
299
+ `list_option_values` to discover its value IDs and presentations for variant
300
+ workflows. These read tools use separate grants and the standard cursor pagination.
301
+
302
+ Use `list_taxons` to discover category IDs. Each item contains `id`, `name`,
303
+ `parent_id`, `taxonomy_id`, and `depth`; roots have a null parent and depth zero.
304
+ The tool requires its own connection grant, `mcp:read`, and Solidus taxon read
305
+ access. It returns only authorized taxons, without expanding ancestors,
306
+ descendants, products, or taxonomy names.
307
+
308
+ Omit `parent_id` to browse all authorized taxons, pass `parent_id: null` to list
309
+ roots, or pass a positive parent ID to list direct children. Add `taxonomy_id`
310
+ to restrict results to an authorized taxonomy, and `query` for a case-insensitive
311
+ literal substring search on taxon names. Explicit parent and taxonomy IDs must
312
+ exist and be readable. Filters combine; a parent outside the selected taxonomy
313
+ returns an empty page. Results use the standard `after_id`/`limit` cursor in ID
314
+ order, which may differ from category display order. Keep the same filters while
315
+ following `next_after_id`. Matching names in different branches are distinguished
316
+ by their parent and taxonomy IDs; no recursive tree response is returned.
317
+
318
+ Call `add_product_to_taxon` with `product_id` and a `taxon_id` discovered through
319
+ `list_taxons`. It requires its own connection grant, `mcp:write`, product update
320
+ access (including the `taxon_ids` attribute), taxon read access, and permission to
321
+ create the classification. New classifications append to the target taxon's
322
+ product ordering through Solidus's normal model workflow. Existing category
323
+ assignments, their positions, and variants are preserved. Repeating a successful
324
+ call returns `attached: true` without adding a duplicate or moving the product.
325
+ Calls through this tool lock the product and target taxon before checking for an
326
+ existing classification; custom classification writers should use the same lock
327
+ order to coordinate changes. The tool does not create taxons or replace the
328
+ product's full category list.
329
+
330
+ To attach an existing option type, call `add_product_option_type` with
331
+ `product_id` and `option_type_id`. It requires its own connection grant,
332
+ `mcp:write` consent, product update access, option-type read access, and permission
333
+ to create the product/option-type association. It preserves existing option types,
334
+ their positions, and variants. Repeating a successful call returns `attached: true`
335
+ without adding a duplicate. Calls through this tool lock the product to serialize
336
+ concurrent attachments; custom association writers should use the same lock.
337
+ Attaching a type does not create option values or variants.
338
+
225
339
  Product creation requires a valid `shipping_category_id`, supplied with the call or through `config.default_shipping_category_id` in your initializer.
226
340
 
227
341
  Price updates require an existing price row, an explicit currency, and `country_iso` (`null` for general-country pricing). Supply decimal amounts as strings, such as `"19.95"`. Bulk updates report success or failure for each entry and can partially succeed. Review the results and retry only failed entries as appropriate.
228
342
 
229
343
  The built-in price update tools use Solidus's standard pricing options. Stores with a custom `pricing_options_class` need a store-specific pricing tool.
230
344
 
231
- Product and price updates take effect immediately. There are currently no built-in order or inventory mutation tools. Add your own, as desired.
345
+ `update_variant` accepts a `variant_id` and a nonempty `changes` object containing
346
+ only `sku`, `weight`, `height`, `width`, `depth`, `cost_price`, or `track_inventory`.
347
+ It works for master and ordinary variants. Supply weight, dimensions, and cost
348
+ price as nonnegative decimal strings with at most two decimal places, for example
349
+ `{"weight": "1.25", "cost_price": "7.99", "track_inventory": false}`. Weight and
350
+ dimensions support up to `999999.99`; cost price supports up to `99999999.99`.
351
+ Omitted fields retain their values; nulls and empty updates are rejected. Cost
352
+ price uses the variant's cost currency under Solidus's normal validation and
353
+ callback behavior. Currency changes are outside this tool's supported fields.
354
+ The tool requires its own grant, `mcp:write`, product and variant update abilities,
355
+ and access to every changed variant attribute. Changes save atomically under a
356
+ variant lock and preserve Solidus validations. Inventory tracking controls whether
357
+ Solidus tracks availability; it does not adjust stock quantities. Selling prices
358
+ continue to use the pricing tools.
359
+
360
+ `list_stock_locations` returns authorized locations, including inactive ones,
361
+ with IDs, names, and `active`, `default`, `fulfillable`, `backorderable_default`,
362
+ `propagate_all_variants`, and `restock_inventory` flags. It uses the standard
363
+ cursor pagination and requires its own grant and `mcp:read` consent. Location IDs
364
+ match `stock_location_id` in existing inventory reads and identify the location
365
+ for `adjust_stock`. Address and contact fields are omitted.
366
+
367
+ `adjust_stock` requires `variant_id`, `stock_location_id`, a nonzero signed integer
368
+ `quantity`, a nonblank `reason` (up to 1,000 characters), and an `idempotency_key`.
369
+ For example:
370
+
371
+ ```json
372
+ {
373
+ "variant_id": 42,
374
+ "stock_location_id": 3,
375
+ "quantity": 5,
376
+ "reason": "Cycle count correction",
377
+ "idempotency_key": "cycle-count-2026-11-12-42-3"
378
+ }
379
+ ```
380
+
381
+ Run `bin/rails solidus_mcp:migrate` before using this tool after upgrading. It
382
+ requires its own connection grant, `mcp:write` consent, read access to the product,
383
+ variant, and location, update access to the stock item and its `count_on_hand`
384
+ attribute, and permission to create the stock movement. The variant/location
385
+ stock item must already exist; the tool never creates one. Inventory tracking
386
+ must be enabled for both the variant and store, and the location must be active
387
+ for a new adjustment. Quantities range from -2147483647 to 2147483647; the resulting
388
+ stock count must fit a signed 32-bit integer.
389
+
390
+ Positive quantities increase stock; negative quantities decrease it. The tool
391
+ creates a standard Solidus stock movement, preserving validations and backorder
392
+ processing. Negative balances are permitted only for backorderable stock items.
393
+ Positive movements may fill outstanding backorders through Solidus callbacks.
394
+ The supplied reason is retained in the movement's `SolidusMcp::StockAdjustment`
395
+ originator, together with the connection identity and saved response.
396
+
397
+ Choose a new key for each intended adjustment. Keys are case-sensitive, up to
398
+ 128 characters, and accept letters, digits, underscores, periods, colons, and
399
+ hyphens. Keys are scoped to the connection (OAuth application and user), so they
400
+ survive token refresh. Retry uncertain or successful requests with the **same key
401
+ and identical inputs**. The movement, count changes, request record, and original
402
+ response commit in one database transaction. Duplicate concurrent requests apply
403
+ once; different keys serialize against the stock item. Reusing a completed key
404
+ with different inputs fails. Failed transactions leave no request record and can
405
+ be retried. Custom database writers and nontransactional side effects in
406
+ store-specific callbacks remain the host application's responsibility.
407
+
408
+ A successful retry checks current grants and record access and returns the
409
+ original movement ID and before/after counts, even if stock later changes or the
410
+ location/tracking flags are disabled. It does not apply another movement. The
411
+ counts describe that adjustment, not a fresh inventory read. Keep the stock
412
+ adjustment records: deleting them removes duplicate-request protection for their
413
+ keys. No automatic expiry or pruning is performed.
414
+
415
+ Product and price updates take effect immediately.
416
+
417
+ ### Product images and availability
418
+
419
+ All four image tools require `product_id`. Omitting `variant_id` selects the
420
+ product's master variant, matching Solidus's product image association. An explicit
421
+ `variant_id` must belong to that product. Sibling variants' images are separate.
422
+ Read calls require product, variant, and image read access. Image writes require
423
+ product and variant update access plus the appropriate image create, update, or
424
+ destroy ability. Each tool has its own connection grant and OAuth scope.
425
+
426
+ `list_product_images` uses ID cursor pagination and returns image IDs, parent IDs,
427
+ positions, alt text, and ActiveStorage content type/byte size. Positions describe
428
+ display order; no signed URLs, storage keys, credentials, or internal paths are
429
+ returned.
430
+
431
+ `attach_product_image` accepts `filename`, `content_type`, `data_base64`, an optional
432
+ `alt`, and `idempotency_key`, in addition to the parent IDs. Supported MIME types
433
+ are `image/png`, `image/jpeg`, `image/gif`, and `image/webp`, subject to the store's
434
+ Solidus image validations. Input must be strict base64, at most 512 KiB decoded,
435
+ with matching detected content type and a plain filename. Remote URLs are not
436
+ accepted. This upload tool supports the standard ActiveStorage adapter; stores
437
+ using a custom attachment adapter need a store-specific upload tool. Uploads
438
+ append to the parent's image list. Use the same key and identical file/metadata
439
+ for retries; changing inputs for a completed key fails. Keys use the stock tool's
440
+ character and length rules and are scoped by connection and tool. Database
441
+ failures roll back image and request records and delete the uploaded object;
442
+ cleanup failures are logged for inspection. As with ordinary ActiveStorage
443
+ uploads, process termination can leave unattached storage objects for store
444
+ maintenance to remove. Successful request records must be retained for retries.
445
+
446
+ `reorder_product_images` accepts the complete `image_ids` array for one parent,
447
+ with at most 100 IDs. Each ID must appear exactly once and be authorized for
448
+ position updates. Partial, foreign, duplicate, and unauthorized lists fail
449
+ atomically. An empty array is valid only for an empty parent. Repeating the same
450
+ order preserves the result. Image writers through these tools lock product then
451
+ variant; custom image writers should coordinate with the same lock order.
452
+
453
+ `remove_product_image` requires `image_id` and its parent context. It permanently
454
+ destroys the image through Solidus callbacks. Standard ActiveStorage attachment
455
+ cleanup may enqueue a purge job; run the store's job workers to remove stored
456
+ files. Missing, foreign, or already removed IDs fail without deleting another
457
+ image. Retrying deletion is safe, but returns an unavailable-record error once
458
+ it has succeeded.
459
+
460
+ `publish_product` and `unpublish_product` each accept `product_id` and require
461
+ separate write grants, product update access, and `available_on` attribute access.
462
+ Publishing sets `available_on` to now if necessary. It refuses already discontinued
463
+ products and preserves any future `discontinue_on` date. Unpublishing sets
464
+ `available_on` to null, preserving discontinuation, variants, and order history.
465
+ Both preserve Solidus validations and are safe to repeat. Publishing changes
466
+ availability, not stock, price, taxon assignment, or store-specific visibility rules.
467
+
468
+ ### Creating price contexts
469
+
470
+ `create_variant_price` requires `variant_id`, `currency`, explicit nullable
471
+ `country_iso`, and nonnegative decimal-string `amount` with at most two decimal
472
+ places (maximum `99999999.99`). It needs its own write grant, product and variant
473
+ update access, and authorization to create the new price. Country-specific prices
474
+ must reference a valid country. Only the standard Solidus `pricing_options_class`
475
+ is supported.
476
+
477
+ Calls lock the variant and check all active rows in the exact currency/country
478
+ context. No existing row means a new validated price is created. One existing
479
+ row with the same amount is returned on retry only when it is readable. Conflicting
480
+ amounts and ambiguous duplicate contexts fail; use the update tools to change
481
+ existing amounts. Custom price creators should use the same variant lock to
482
+ coordinate context creation. The tool does not modify existing or discarded rows.
483
+
484
+ ### Cancellation, shipping, and refunds
485
+
486
+ Run `bin/rails solidus_mcp:migrate` after upgrading before using upload or external
487
+ workflow tools. All three external workflow tools require their own write grant,
488
+ `mcp:write`, a connection-scoped `idempotency_key`, and record authorization for
489
+ the affected workflow. Keys follow the same character/length rules as stock
490
+ adjustments and are scoped by connection and tool; retain their request records.
491
+ They must run outside any caller-managed database transaction so their durable
492
+ claims commit before gateway, notification, or fulfillment callbacks run.
493
+
494
+ `cancel_order` requires `order_id` and a nonblank `reason` (up to 1,000 characters).
495
+ Only completed, Solidus-cancellable orders whose shipments are all pending or
496
+ ready may be newly canceled. Already canceled orders return their canceled state.
497
+ The tool uses `canceled_by`, preserving Solidus restocking, payment void/refund,
498
+ callbacks, actor attribution, and canceled timestamps. The supplied reason is
499
+ retained in the request audit; Solidus's payment canceller keeps its standard
500
+ refund-reason behavior. Authorization includes the order cancel action, affected
501
+ shipments, payments and potential refunds/reasons, stock items/movements, variants,
502
+ products, locations, and inventory units affected by restocking/backorders. It
503
+ never forces an arbitrary state or cancels already shipped fulfillment.
504
+
505
+ `ship_shipment` requires `shipment_id` and explicit boolean `notify_customer`;
506
+ `tracking` is optional and, when supplied, requires tracking attribute update
507
+ access. New fulfillment requires a ready shipment on a completed order, with
508
+ on-hand units and no unresolved backorders. The tool calls Solidus's shipment
509
+ shipping event, creating a carton and shipping its eligible inventory units.
510
+ It fulfills the selected shipment while Solidus recalculates the order's overall
511
+ state. It does not decrement stock again; reservation happened in the normal
512
+ order workflow. Permissions cover the order, shipment, inventory units, variants,
513
+ products, shipping address/method, location, and prospective carton. Notifications
514
+ use the standard Solidus subscriber and are suppressed when `notify_customer` is
515
+ false. Already shipped shipments do not create another carton; conflicting new
516
+ tracking is rejected. Store-specific subscribers retain their usual behavior.
517
+
518
+ `refund_payment` requires `payment_id`, `refund_reason_id`, `currency`, and a
519
+ positive decimal-string `amount` with at most two decimal places. Currency must
520
+ match the payment, and the amount must be exactly representable in that currency's
521
+ minor units. The tool supports partial refunds, completed payments only, and
522
+ amounts no greater than remaining credit. It locks order then payment and uses
523
+ Solidus's refund validation and `perform!` workflow. It requires order/payment
524
+ update access, refund-reason read access, and authorization for the new refund.
525
+ Responses contain refund/payment IDs, amount, currency, and success, excluding
526
+ gateway authorization codes, source data, customer contact details, and raw
527
+ provider responses. Solidus retains its normal refund logs and reason records.
528
+
529
+ Each external workflow commits a `SolidusMcp::ToolRequest` claim before starting.
530
+ Successful calls save their original result and return it on identical retries,
531
+ checking current access first. Changing inputs under the same key fails. An
532
+ order-wide database guard prevents overlapping external operations, including
533
+ calls made through different connections. Failures before effects begin mark the
534
+ request `failed` and can be retried. Once a callback or gateway call might have
535
+ run, failure marks the request `uncertain`. A process crash can leave it
536
+ `processing`. Both states block further external workflow calls for that order,
537
+ including new keys: they never automatically reissue a potentially completed
538
+ refund, void, notification, or fulfillment operation.
539
+
540
+ For reconciliation, a trusted operator must inspect the request ID, payload,
541
+ connection, timestamps, Solidus records, gateway logs, and actual fulfillment or
542
+ notification outcome. Preserve that audit and correct any database state to match
543
+ the verified external result before resolving the request through trusted
544
+ application code. A confirmed success needs a `succeeded` status and original
545
+ result; `failed` is appropriate only after confirming no external effect occurred.
546
+ Do not delete a request or change its status merely to bypass the guard. These
547
+ protections coordinate MCP tools; custom integrations and manual gateway actions
548
+ must be reconciled separately.
232
549
 
233
550
  ## Custom serializers
234
551
 
@@ -361,6 +678,7 @@ These declarations form the gem's Ruby DSL for describing tools:
361
678
  | `category 'Products'` | Yes | Groups the tool in the permissions interface. |
362
679
  | `permission 'count_products'` | Yes | Unique key used for permission grants. Accepts the same characters as tool names, plus periods. |
363
680
  | `read_only true` | Yes | Use `true` for read tools requiring `mcp:read`, or `false` for write tools requiring `mcp:write`. This declaration does not itself prevent database writes. |
681
+ | `audit_action "create"` | No | Classify writes as `create`, `update`, or `delete` in activity history. Read tools default to `read`; other writes default to `update`. Must agree with `read_only`. |
364
682
  | `ability :read, 'Spree::Product'` | At least one | Required Solidus ability. Repeat for additional abilities; all must pass. |
365
683
  | `input :query, type: 'string', required: true` | No | Declares an argument and its JSON Schema constraints. Repeat for each argument the tool accepts. |
366
684
 
@@ -282,3 +282,42 @@ solidus-mcp-account-search [hidden] {
282
282
  cursor: default;
283
283
  opacity: 0.5;
284
284
  }
285
+
286
+ .solidus-mcp-admin .solidus-mcp-activity-filters {
287
+ display: grid;
288
+ grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
289
+ gap: 1rem;
290
+ margin: 1.5rem 0;
291
+ }
292
+
293
+ .solidus-mcp-admin .solidus-mcp-activity-filters label {
294
+ display: block;
295
+ margin-bottom: 0.35rem;
296
+ font-weight: 600;
297
+ }
298
+
299
+ .solidus-mcp-admin .solidus-mcp-activity-filters input:not([type="submit"]),
300
+ .solidus-mcp-admin .solidus-mcp-activity-filters select {
301
+ width: 100%;
302
+ min-height: 2.5rem;
303
+ box-sizing: border-box;
304
+ border: 1px solid #6b7280;
305
+ border-radius: 0.25rem;
306
+ padding: 0.4rem;
307
+ }
308
+
309
+ .solidus-mcp-admin .solidus-mcp-activity-filter-actions {
310
+ align-self: end;
311
+ }
312
+
313
+ .solidus-mcp-admin .solidus-mcp-activity-groups {
314
+ display: flex;
315
+ flex-wrap: wrap;
316
+ gap: 1rem;
317
+ margin: 1rem 0;
318
+ }
319
+
320
+ .solidus-mcp-admin .solidus-mcp-activity-groups [aria-current="page"] {
321
+ font-weight: 700;
322
+ text-decoration-thickness: 0.2rem;
323
+ }
@@ -0,0 +1,77 @@
1
+ /* Standalone OAuth screen, sharing the MCP admin palette and controls. */
2
+ .solidus-mcp-consent {
3
+ margin: 0;
4
+ padding: 3rem 1rem;
5
+ background: #f5f3f0;
6
+ color: #222222;
7
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
8
+ font-size: 1rem;
9
+ line-height: 1.5;
10
+ }
11
+
12
+ .solidus-mcp-consent .solidus-mcp-consent-card {
13
+ max-width: 44rem;
14
+ margin: 0 auto;
15
+ padding: 2rem;
16
+ border: 1px solid #d8dad8;
17
+ border-radius: 0.5rem;
18
+ background: #ffffff;
19
+ box-shadow: 0 0.25rem 1rem rgba(0, 0, 0, 0.04);
20
+ overflow-wrap: anywhere;
21
+ }
22
+
23
+ .solidus-mcp-consent-address,
24
+ .solidus-mcp-consent-scope {
25
+ padding: 1rem;
26
+ border: 1px solid #d8dad8;
27
+ border-radius: 0.25rem;
28
+ background: #f5f3f0;
29
+ }
30
+
31
+ .solidus-mcp-consent-access {
32
+ display: grid;
33
+ gap: 1rem;
34
+ margin: 1.5rem 0;
35
+ }
36
+
37
+ .solidus-mcp-consent-scope ul {
38
+ margin: 0;
39
+ padding-left: 1.25rem;
40
+ }
41
+
42
+ .solidus-mcp-consent-scope li + li {
43
+ margin-top: 0.375rem;
44
+ }
45
+
46
+ .solidus-mcp-consent-actions {
47
+ display: flex;
48
+ flex-wrap: wrap;
49
+ gap: 0.75rem;
50
+ margin: 1.5rem 0 2rem;
51
+ }
52
+
53
+ .solidus-mcp-consent-review {
54
+ padding-top: 1.5rem;
55
+ border-top: 1px solid #d8dad8;
56
+ }
57
+
58
+ .solidus-mcp-consent-review summary {
59
+ font-weight: 600;
60
+ }
61
+
62
+ .solidus-mcp-consent-choice {
63
+ display: flex;
64
+ align-items: baseline;
65
+ gap: 0.625rem;
66
+ cursor: pointer;
67
+ }
68
+
69
+ @media (max-width: 40rem) {
70
+ .solidus-mcp-consent {
71
+ padding: 1rem 0.5rem;
72
+ }
73
+
74
+ .solidus-mcp-consent .solidus-mcp-consent-card {
75
+ padding: 1.25rem;
76
+ }
77
+ }
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusAdmin
4
+ class McpActivityController < BaseController
5
+ before_action :require_mcp_user
6
+
7
+ def index
8
+ @filters = params.permit(:user, :tool, :action_type, :outcome, :from, :to, :before_id).to_h
9
+ events = SolidusMcp::ActivityEvent.visible_to(current_solidus_admin_user)
10
+ if @filters["user"].present?
11
+ value = @filters["user"].first(255)
12
+ if value.match?(/\A[0-9]{1,18}\z/)
13
+ events = events.where(user_id: value.to_i)
14
+ else
15
+ pattern = "%#{ActiveRecord::Base.sanitize_sql_like(value)}%"
16
+ events = events.where(user_id: Spree.user_class.where("email ILIKE ?", pattern).select(:id))
17
+ end
18
+ end
19
+ events = events.where(tool_name: @filters["tool"].first(128)) if @filters["tool"].present?
20
+ if @filters["outcome"].present?
21
+ raise ActionController::BadRequest, "Invalid outcome" unless SolidusMcp::ActivityEvent::STATUSES.include?(@filters["outcome"])
22
+ events = events.where(status: @filters["outcome"])
23
+ end
24
+ from = filter_time(@filters["from"])
25
+ to = filter_time(@filters["to"])
26
+ raise ActionController::BadRequest, "Invalid time range" if from && to && from > to
27
+ events = events.where("started_at >= ?", from) if from
28
+ events = events.where("started_at <= ?", to) if to
29
+ @filters["from"] = from.in_time_zone.strftime("%Y-%m-%dT%H:%M:%S") if from
30
+ @filters["to"] = to.in_time_zone.strftime("%Y-%m-%dT%H:%M:%S") if to
31
+ @counts = events.group(:action).count
32
+ if @filters["action_type"].present?
33
+ raise ActionController::BadRequest, "Invalid action type" unless SolidusMcp::ActivityEvent::ACTIONS.include?(@filters["action_type"])
34
+ events = events.where(action: @filters["action_type"])
35
+ end
36
+ if @filters["before_id"].present?
37
+ raise ActionController::BadRequest, "Invalid cursor" unless @filters["before_id"].match?(/\A[1-9][0-9]{0,17}\z/)
38
+ events = events.where("id < ?", @filters["before_id"].to_i)
39
+ end
40
+ @events = events.order(id: :desc).limit(51).to_a
41
+ @more = @events.size > 50
42
+ @events = @events.first(50)
43
+ @users = Spree.user_class.where(id: @events.map(&:user_id)).index_by(&:id)
44
+ end
45
+
46
+ private
47
+
48
+ def authorization_subject
49
+ :mcp_connections
50
+ end
51
+
52
+ def require_mcp_user
53
+ head :forbidden unless SolidusMcp::Administration.user?(current_solidus_admin_user)
54
+ end
55
+
56
+ def filter_time(value)
57
+ return if value.blank?
58
+ unless value.match?(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?(?:Z|[+-]\d{2}:\d{2})?\z/)
59
+ raise ActionController::BadRequest, "Invalid time filter"
60
+ end
61
+ parsed = DateTime.iso8601(value)
62
+ value.match?(/(?:Z|[+-]\d{2}:\d{2})\z/) ? parsed.to_time : Time.zone.local(parsed.year, parsed.month, parsed.day, parsed.hour, parsed.minute, parsed.second)
63
+ rescue ArgumentError
64
+ raise ActionController::BadRequest, "Invalid time filter"
65
+ end
66
+ end
67
+ end