solidus_mcp 0.2.0.rc1 → 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 (57) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +71 -0
  3. data/CONTRIBUTING.md +51 -4
  4. data/README.md +412 -3
  5. data/app/assets/stylesheets/solidus_mcp/admin.css +39 -0
  6. data/app/assets/stylesheets/solidus_mcp/consent.css +77 -0
  7. data/app/controllers/solidus_admin/mcp_activity_controller.rb +67 -0
  8. data/app/controllers/solidus_mcp/endpoint_controller.rb +36 -0
  9. data/app/models/solidus_mcp/activity_event.rb +37 -0
  10. data/app/models/solidus_mcp/audit_context.rb +7 -0
  11. data/app/models/solidus_mcp/stock_adjustment.rb +16 -0
  12. data/app/models/solidus_mcp/tool_request.rb +10 -0
  13. data/app/services/solidus_mcp/action_audit.rb +169 -0
  14. data/app/services/solidus_mcp/image_context.rb +44 -0
  15. data/app/services/solidus_mcp/order_workflow_authorization.rb +76 -0
  16. data/app/services/solidus_mcp/serializers.rb +28 -4
  17. data/app/services/solidus_mcp/tool_request_execution.rb +76 -0
  18. data/app/tools/solidus_mcp/tools/add_product_option_type.rb +36 -0
  19. data/app/tools/solidus_mcp/tools/add_product_to_taxon.rb +40 -0
  20. data/app/tools/solidus_mcp/tools/adjust_stock.rb +98 -0
  21. data/app/tools/solidus_mcp/tools/attach_product_image.rb +77 -0
  22. data/app/tools/solidus_mcp/tools/bulk_update_variant_prices.rb +1 -1
  23. data/app/tools/solidus_mcp/tools/cancel_order.rb +44 -0
  24. data/app/tools/solidus_mcp/tools/create_product.rb +1 -0
  25. data/app/tools/solidus_mcp/tools/create_variant_price.rb +59 -0
  26. data/app/tools/solidus_mcp/tools/list_option_types.rb +34 -0
  27. data/app/tools/solidus_mcp/tools/list_option_values.rb +27 -0
  28. data/app/tools/solidus_mcp/tools/list_product_images.rb +26 -0
  29. data/app/tools/solidus_mcp/tools/list_shipping_categories.rb +24 -0
  30. data/app/tools/solidus_mcp/tools/list_stock_locations.rb +27 -0
  31. data/app/tools/solidus_mcp/tools/list_taxons.rb +40 -0
  32. data/app/tools/solidus_mcp/tools/publish_product.rb +32 -0
  33. data/app/tools/solidus_mcp/tools/refund_payment.rb +63 -0
  34. data/app/tools/solidus_mcp/tools/remove_product_image.rb +33 -0
  35. data/app/tools/solidus_mcp/tools/reorder_product_images.rb +41 -0
  36. data/app/tools/solidus_mcp/tools/ship_shipment.rb +63 -0
  37. data/app/tools/solidus_mcp/tools/unpublish_product.rb +29 -0
  38. data/app/tools/solidus_mcp/tools/update_variant.rb +54 -0
  39. data/app/tools/solidus_mcp/tools/update_variant_price.rb +1 -1
  40. data/app/views/solidus_admin/mcp_activity/index.html.erb +53 -0
  41. data/app/views/solidus_admin/mcp_connections/index.html.erb +2 -0
  42. data/app/views/solidus_mcp/authorizations/new.html.erb +59 -41
  43. data/config/routes.rb +1 -0
  44. data/db/migrate/20261112000000_create_solidus_mcp_stock_adjustments.rb +19 -0
  45. data/db/migrate/20261112010000_create_solidus_mcp_tool_requests.rb +19 -0
  46. data/db/migrate/20261112020000_create_solidus_mcp_activity_events.rb +34 -0
  47. data/db/migrate/20261112020100_add_actor_role_to_mcp_activity_events.rb +7 -0
  48. data/lib/solidus_mcp/audited_server.rb +25 -0
  49. data/lib/solidus_mcp/configuration.rb +19 -1
  50. data/lib/solidus_mcp/engine.rb +9 -3
  51. data/lib/solidus_mcp/policy.rb +6 -2
  52. data/lib/solidus_mcp/registry.rb +5 -2
  53. data/lib/solidus_mcp/server.rb +1 -2
  54. data/lib/solidus_mcp/tool.rb +9 -7
  55. data/lib/solidus_mcp/version.rb +1 -1
  56. data/lib/solidus_mcp.rb +5 -1
  57. metadata +37 -2
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ module Tools
5
+ class RefundPayment < Base
6
+ tool_name :refund_payment
7
+ description "Refund an explicit payment amount and currency through Solidus. Requires refund_reason_id and an idempotency key. Uncertain gateway outcomes block further external operations on the order until reconciled."
8
+ category "Orders"
9
+ permission "refund_payment"
10
+ read_only false
11
+ audit_action "create"
12
+ ability :update, "Spree::Order"
13
+ ability :update, "Spree::Payment"
14
+ ability :read, "Spree::RefundReason"
15
+ ability :create, "Spree::Refund"
16
+ input :payment_id, type: "integer", minimum: 1, required: true
17
+ input :refund_reason_id, type: "integer", minimum: 1, required: true
18
+ input :currency, type: "string", pattern: "^[A-Z]{3}$", required: true
19
+ input :amount, type: "string", required: true
20
+ input :idempotency_key, type: "string", minLength: 1, maxLength: 128, required: true
21
+
22
+ protected
23
+
24
+ def call(payment_id:, refund_reason_id:, currency:, amount:, idempotency_key:)
25
+ unless amount.match?(/\A(?:0|[1-9][0-9]{0,7})(?:\.[0-9]{1,2})?\z/) && BigDecimal(amount).positive?
26
+ raise ToolError, "Amount must be a positive decimal string with at most two decimal places"
27
+ end
28
+ payment = policy.scope(Spree::Payment, :update)
29
+ .where(order_id: policy.scope(Spree::Order, :update).select(:id)).find(payment_id)
30
+ order = payment.order
31
+ reason = policy.authorize_record!(:read, policy.scope(Spree::RefundReason).find(refund_reason_id))
32
+ refund = Spree::Refund.new(payment_id: payment.id, refund_reason_id: reason.id, amount: BigDecimal(amount))
33
+ policy.authorize_record!(:create, refund)
34
+ policy.authorize_record!(:update, payment.order)
35
+ unless currency.match?(/\A[A-Z]{3}\z/) && payment.currency == currency && refund.money.cents == BigDecimal(amount) * refund.money.currency.subunit_to_unit
36
+ raise ToolError, "Currency must match the payment and support the requested cent precision"
37
+ end
38
+ request = ToolRequestExecution.new(credential, operation: "refund_payment", key: idempotency_key,
39
+ payload: {payment_id: payment_id, refund_reason_id: refund_reason_id, currency: currency, amount: amount})
40
+ request.external(guard_key: "order:#{order.id}") do |effects|
41
+ order.with_lock do
42
+ payment.with_lock do
43
+ authorize!
44
+ raise ToolError, "Payment order changed; retrieve it again" unless payment.order_id == order.id
45
+ policy.authorize_record!(:update, payment.order)
46
+ policy.authorize_record!(:update, payment)
47
+ policy.authorize_record!(:read, reason.reload)
48
+ unless payment.completed? && payment.currency == currency && BigDecimal(amount) <= payment.credit_allowed
49
+ raise ToolError, "Payment is not refundable for the requested amount and currency"
50
+ end
51
+ refund = Spree::Refund.new(payment_id: payment.id, refund_reason_id: reason.id, amount: BigDecimal(amount))
52
+ policy.authorize_record!(:create, refund)
53
+ refund.save!
54
+ effects.call
55
+ refund.perform!
56
+ {refund_id: refund.id, payment_id: payment.id, amount: refund.amount.to_s("F"), currency: currency, refunded: true}
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ module Tools
5
+ class RemoveProductImage < Base
6
+ tool_name :remove_product_image
7
+ description "Permanently remove one image from an explicit product/variant parent. Missing or already removed IDs fail safely; attachment cleanup follows Solidus and ActiveStorage callbacks."
8
+ category "Products"
9
+ permission "remove_product_image"
10
+ read_only false
11
+ audit_action "delete"
12
+ ability :update, "Spree::Product"
13
+ ability :update, "Spree::Variant"
14
+ ability :destroy, "Spree::Image"
15
+ input :product_id, type: "integer", minimum: 1, required: true
16
+ input :variant_id, type: "integer", minimum: 1
17
+ input :image_id, type: "integer", minimum: 1, required: true
18
+
19
+ protected
20
+
21
+ def call(product_id:, image_id:, variant_id: nil)
22
+ context = ImageContext.new(policy, product_id: product_id, variant_id: variant_id, action: :update)
23
+ context.with_lock do
24
+ authorize!
25
+ image = context.images(:destroy).find(image_id)
26
+ policy.authorize_record!(:destroy, image)
27
+ image.destroy!
28
+ end
29
+ {image_id: image_id, removed: true}
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ module Tools
5
+ class ReorderProductImages < Base
6
+ tool_name :reorder_product_images
7
+ description "Replace the complete image ordering for one product master or explicit variant. All image IDs must be supplied exactly once; changes are atomic."
8
+ category "Products"
9
+ permission "reorder_product_images"
10
+ read_only false
11
+ ability :update, "Spree::Product"
12
+ ability :update, "Spree::Variant"
13
+ ability :update, "Spree::Image"
14
+ input :product_id, type: "integer", minimum: 1, required: true
15
+ input :variant_id, type: "integer", minimum: 1
16
+ input :image_ids, type: "array", items: {type: "integer", minimum: 1}, uniqueItems: true, maxItems: 100, required: true
17
+
18
+ protected
19
+
20
+ def call(product_id:, image_ids:, variant_id: nil)
21
+ context = ImageContext.new(policy, product_id: product_id, variant_id: variant_id, action: :update)
22
+ context.with_lock do
23
+ authorize!
24
+ # Check the complete parent collection, not just its readable subset.
25
+ actual = Spree::Image.where(viewable: context.variant).limit(101).pluck(:id)
26
+ unless actual.sort == image_ids.sort
27
+ raise ToolError, "Supply every image in this parent exactly once"
28
+ end
29
+ images = context.images(:update).where(id: image_ids).index_by(&:id)
30
+ raise AccessDenied, "Record is unavailable" unless images.length == actual.length
31
+ image_ids.each do |id|
32
+ policy.authorize_record!(:update, images.fetch(id), attribute: :position)
33
+ end
34
+ image_ids.each_with_index { |id, index| images.fetch(id).insert_at(index + 1) }
35
+ images.each_value { |image| policy.authorize_record!(:update, image.reload, attribute: :position) }
36
+ end
37
+ {product_id: product_id, variant_id: context.variant.id, image_ids: image_ids}
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ module Tools
5
+ class ShipShipment < Base
6
+ tool_name :ship_shipment
7
+ description "Ship one ready shipment through Solidus carton fulfillment. Explicitly choose notify_customer; tracking is optional. Requires an idempotency key and record permissions for affected fulfillment records."
8
+ category "Orders"
9
+ permission "ship_shipment"
10
+ read_only false
11
+ ability :update, "Spree::Order"
12
+ ability :ship, "Spree::Shipment"
13
+ ability :update, "Spree::InventoryUnit"
14
+ ability :create, "Spree::Carton"
15
+ input :shipment_id, type: "integer", minimum: 1, required: true
16
+ input :tracking, type: "string", minLength: 1, maxLength: 255
17
+ input :notify_customer, type: "boolean", required: true
18
+ input :idempotency_key, type: "string", minLength: 1, maxLength: 128, required: true
19
+
20
+ protected
21
+
22
+ def call(shipment_id:, notify_customer:, idempotency_key:, tracking: nil)
23
+ shipment = policy.scope(Spree::Shipment, :ship)
24
+ .where(order_id: policy.scope(Spree::Order, :update).select(:id)).find(shipment_id)
25
+ order = shipment.order
26
+ authorization = OrderWorkflowAuthorization.new(policy)
27
+ authorization.shipping(shipment, tracking: tracking || shipment.tracking, notify_customer: notify_customer)
28
+ request = ToolRequestExecution.new(credential, operation: "ship_shipment", key: idempotency_key,
29
+ payload: {shipment_id: shipment_id, tracking: tracking, notify_customer: notify_customer})
30
+ request.external(guard_key: "order:#{order.id}") do |effects|
31
+ order.with_lock do
32
+ shipment.with_lock do
33
+ authorize!
34
+ raise ToolError, "Shipment order changed; retrieve it again" unless shipment.order_id == order.id
35
+ units = shipment.inventory_units.reload.to_a
36
+ units.each(&:lock!)
37
+ authorization.shipping(shipment, tracking: tracking || shipment.tracking, notify_customer: notify_customer)
38
+ if shipment.shipped?
39
+ if tracking && tracking != shipment.tracking
40
+ raise ToolError, "Shipment is already shipped with different tracking"
41
+ end
42
+ else
43
+ eligible = shipment.state == "ready" && shipment.order.completed? && units.any?(&:on_hand?) &&
44
+ units.all? { |unit| unit.on_hand? || unit.shipped? || unit.canceled? }
45
+ unless eligible
46
+ raise ToolError, "Shipment must be ready on a completed order, with shippable units and no backorders"
47
+ end
48
+ policy.authorize_record!(:update, shipment, attribute: :tracking) if tracking
49
+ shipment.tracking = tracking if tracking
50
+ policy.authorize_record!(:ship, shipment)
51
+ policy.authorize_record!(:update, shipment, attribute: :tracking) if tracking
52
+ shipment.suppress_mailer = !notify_customer
53
+ effects.call
54
+ shipment.ship!
55
+ end
56
+ {shipment_id: shipment.id, order_id: shipment.order_id, state: shipment.state, tracking: shipment.tracking}
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ module Tools
5
+ class UnpublishProduct < Base
6
+ tool_name :unpublish_product
7
+ description "Withdraw product availability without deleting it, its variants, or order history."
8
+ category "Products"
9
+ permission "unpublish_product"
10
+ read_only false
11
+ ability :update, "Spree::Product"
12
+ input :product_id, type: "integer", minimum: 1, required: true
13
+
14
+ protected
15
+
16
+ def call(product_id:)
17
+ product = policy.scope(Spree::Product, :update).find(product_id)
18
+ product.with_lock do
19
+ authorize!
20
+ policy.authorize_record!(:update, product, attribute: :available_on)
21
+ product.available_on = nil
22
+ policy.authorize_record!(:update, product, attribute: :available_on)
23
+ product.save! if product.changed?
24
+ end
25
+ {product_id: product.id, available: !!product.available?}
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ module Tools
5
+ class UpdateVariant < Base
6
+ tool_name :update_variant
7
+ description "Update variant SKU, weight, dimensions, cost price, or inventory tracking. Decimals are nonnegative strings with at most two decimal places. Changes take effect immediately."
8
+ category "Products"
9
+ permission "update_variant"
10
+ read_only false
11
+ ability :update, "Spree::Product"
12
+ ability :update, "Spree::Variant"
13
+ input :variant_id, type: "integer", minimum: 1, required: true
14
+ input :changes, type: "object", minProperties: 1, additionalProperties: false, required: true,
15
+ properties: {sku: {type: "string", minLength: 1, maxLength: 255},
16
+ weight: {type: "string", pattern: "^(0|[1-9][0-9]{0,5})(\\.[0-9]{1,2})?$", maxLength: 9},
17
+ height: {type: "string", pattern: "^(0|[1-9][0-9]{0,5})(\\.[0-9]{1,2})?$", maxLength: 9},
18
+ width: {type: "string", pattern: "^(0|[1-9][0-9]{0,5})(\\.[0-9]{1,2})?$", maxLength: 9},
19
+ depth: {type: "string", pattern: "^(0|[1-9][0-9]{0,5})(\\.[0-9]{1,2})?$", maxLength: 9},
20
+ cost_price: {type: "string", pattern: "^(0|[1-9][0-9]{0,7})(\\.[0-9]{1,2})?$", maxLength: 11},
21
+ track_inventory: {type: "boolean"}}
22
+
23
+ protected
24
+
25
+ def call(variant_id:, changes:)
26
+ attributes = changes.symbolize_keys
27
+ %i[weight height width depth cost_price].each do |attribute|
28
+ next unless attributes.key?(attribute)
29
+ digits = (attribute == :cost_price) ? 8 : 6
30
+ unless attributes[attribute].match?(/\A(?:0|[1-9][0-9]{0,#{digits - 1}})(?:\.[0-9]{1,2})?\z/)
31
+ raise ToolError, "#{attribute} must be a nonnegative decimal string with at most two decimal places"
32
+ end
33
+ attributes[attribute] = BigDecimal(attributes[attribute])
34
+ end
35
+ variant = policy.scope(Spree::Variant, :update)
36
+ .where(product_id: policy.scope(Spree::Product, :update).select(:id)).find(variant_id)
37
+ variant.with_lock do
38
+ authorize!
39
+ policy.authorize_record!(:update, variant.product)
40
+ authorize_attributes!(variant, attributes)
41
+ variant.assign_attributes(attributes)
42
+ authorize_attributes!(variant, attributes)
43
+ variant.save!
44
+ end
45
+ {variant_id: variant.id, updated: true}
46
+ end
47
+
48
+ def authorize_attributes!(variant, attributes)
49
+ policy.authorize_record!(:update, variant)
50
+ attributes.each_key { |attribute| policy.authorize_record!(:update, variant, attribute: attribute) }
51
+ end
52
+ end
53
+ end
54
+ end
@@ -13,7 +13,7 @@ module SolidusMcp
13
13
  ability :update, "Spree::Price"
14
14
  input :variant_id, type: "integer", minimum: 1, required: true
15
15
  input :currency, type: "string", pattern: "^[A-Z]{3}$", required: true
16
- input :country_iso, type: ["string", "null"], pattern: "^[A-Z]{2}$", required: true
16
+ input :country_iso, anyOf: [{type: "string", pattern: "^[A-Z]{2}$"}, {type: "null"}], required: true
17
17
  input :amount, type: "string", required: true
18
18
 
19
19
  protected
@@ -0,0 +1,53 @@
1
+ <%= stylesheet_link_tag "solidus_mcp/admin", "data-turbo-track": "reload" %>
2
+ <div class="solidus-mcp-admin">
3
+ <h1 class="solidus-mcp-page-title">MCP activity</h1>
4
+ <p class="solidus-mcp-intro">Review which user and client performed each action, its targets, and whether it succeeded. Your MCP administration role determines whose activity is visible.</p>
5
+ <p><%= link_to "AI connections", solidus_admin.mcp_connections_path %></p>
6
+
7
+ <%= form_with url: solidus_admin.mcp_activity_index_path, method: :get, local: true, class: "solidus-mcp-activity-filters" do %>
8
+ <div><%= label_tag :user, "User (email or ID)" %><%= text_field_tag :user, @filters["user"], maxlength: 255 %></div>
9
+ <div><%= label_tag :tool, "Tool" %><%= text_field_tag :tool, @filters["tool"], maxlength: 128, placeholder: "get_product" %></div>
10
+ <div><%= label_tag :outcome, "Outcome" %><%= select_tag :outcome, options_for_select([["All outcomes", ""], ["Succeeded", "succeeded"], ["Partially succeeded", "partial"], ["Denied", "denied"], ["Failed", "failed"], ["Unfinished", "started"]], @filters["outcome"]) %></div>
11
+ <div><%= label_tag :from, "From (#{Time.zone.name})" %><%= datetime_local_field_tag :from, @filters["from"], step: 1 %></div>
12
+ <div><%= label_tag :to, "To (#{Time.zone.name})" %><%= datetime_local_field_tag :to, @filters["to"], step: 1 %></div>
13
+ <%= hidden_field_tag :action_type, @filters["action_type"] if @filters["action_type"].present? %>
14
+ <div class="solidus-mcp-activity-filter-actions"><%= submit_tag "Filter" %> <%= link_to "Clear", solidus_admin.mcp_activity_index_path %></div>
15
+ <% end %>
16
+
17
+ <nav class="solidus-mcp-activity-groups" aria-label="Action types">
18
+ <%= link_to "All (#{@counts.values.sum})", solidus_admin.mcp_activity_index_path(@filters.except("action_type", "before_id")), aria: {current: @filters["action_type"].blank? ? "page" : nil} %>
19
+ <% SolidusMcp::ActivityEvent::ACTIONS.each do |action| %>
20
+ <%= link_to "#{action.titleize} (#{@counts.fetch(action, 0)})", solidus_admin.mcp_activity_index_path(@filters.except("before_id").merge("action_type" => action)), aria: {current: @filters["action_type"] == action ? "page" : nil} %>
21
+ <% end %>
22
+ </nav>
23
+
24
+ <div class="solidus-mcp-table-scroll">
25
+ <table class="solidus-mcp-table">
26
+ <thead><tr><th scope="col">Time</th><th scope="col">User</th><th scope="col">Client</th><th scope="col">Action</th><th scope="col">Outcome</th><th scope="col">Duration</th><th scope="col">Details</th></tr></thead>
27
+ <tbody>
28
+ <% @events.each do |event| %>
29
+ <tr data-event-id="<%= event.event_id %>">
30
+ <td><time datetime="<%= event.started_at.iso8601 %>"><%= event.started_at.in_time_zone.strftime("%Y-%m-%d %H:%M:%S %Z") %></time></td>
31
+ <td><%= @users[event.user_id]&.email || "User ##{event.user_id}" %></td>
32
+ <td><%= event.application_name.presence || "Client ##{event.application_id}" %></td>
33
+ <td><strong><%= event.action.titleize %></strong><br><code><%= event.tool_name || event.protocol_method %></code></td>
34
+ <td><%= event.status == "started" ? "Unfinished" : event.status.titleize %></td>
35
+ <td><%= event.duration_ms ? "#{event.duration_ms} ms" : "—" %></td>
36
+ <td><details><summary>View details</summary>
37
+ <p>Event: <code><%= event.event_id %></code></p>
38
+ <% if event.request_id.present? %><p>Request: <code><%= event.request_id %></code></p><% end %>
39
+ <% if event.resource_ids.present? %><p>Targets: <code><%= event.resource_ids.to_json %></code></p><% end %>
40
+ <% if event.changed_fields.present? %><p>Requested fields: <%= event.changed_fields.join(", ") %></p><% end %>
41
+ <% if event.error_class.present? %><p>Error type: <code><%= event.error_class %></code></p><% end %>
42
+ </details></td>
43
+ </tr>
44
+ <% end %>
45
+ </tbody>
46
+ </table>
47
+ </div>
48
+ <% if @events.empty? %><p class="solidus-mcp-empty-state">No activity matches these filters.</p><% end %>
49
+ <nav class="solidus-mcp-pagination" aria-label="Activity pages">
50
+ <% if @filters["before_id"].present? %><%= link_to "Newest", solidus_admin.mcp_activity_index_path(@filters.except("before_id")) %><% end %>
51
+ <% if @more %><%= link_to "Older", solidus_admin.mcp_activity_index_path(@filters.merge("before_id" => @events.last.id)) %><% end %>
52
+ </nav>
53
+ </div>
@@ -9,6 +9,8 @@
9
9
  "You are an MCP user. Only your own connections are shown; an MCP administrator manages their permissions."
10
10
  end %> Permissions also remain limited by the connection owner's store access and OAuth consent.</p>
11
11
 
12
+ <p><%= link_to "MCP activity", solidus_admin.mcp_activity_index_path %></p>
13
+
12
14
  <% if mcp_superadministrator? %>
13
15
  <p><%= link_to "Manage MCP administrators", solidus_admin.mcp_administrators_path %></p>
14
16
  <% end %>
@@ -1,43 +1,61 @@
1
1
  <!DOCTYPE html>
2
2
  <html lang="en">
3
- <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Connect to your Solidus store</title></head>
4
- <body><main>
5
- <h1>Connect <%= @pre_auth.client.application.name %> to your Solidus store</h1>
6
- <p>Approve only if you started this connection. The client supplies its name.</p>
7
- <p>Return address: <%= @pre_auth.redirect_uri %></p>
8
- <% if @pre_auth.scopes.include?("mcp:read") %>
9
- <h2>Read access</h2>
10
- <ul><li>Search products and variants.</li><li>View prices and inventory.</li><li>Read order information.</li></ul>
11
- <% end %>
12
- <% if @pre_auth.scopes.include?("mcp:write") %>
13
- <h2>Write access</h2>
14
- <ul><li>Modify product information.</li><li>Update prices.</li><li>Perform other explicitly enabled store-management operations.</li></ul>
15
- <% end %>
16
- <p>Administrators must also enable individual tools in AI connections. They can change enabled tools within this access level without reconnecting.</p>
17
- <% {"Authorize" => :post, "Deny" => :delete}.each do |label, method| %>
18
- <%= form_tag "#{SolidusMcp.configuration.endpoint_url}/oauth/authorize", method: method do %>
19
- <% %i[client_id redirect_uri state response_type scope code_challenge code_challenge_method resource].each do |key| %>
20
- <%= hidden_field_tag key, params[key], id: nil %>
21
- <% end %>
22
- <%= submit_tag label %>
23
- <% end %>
24
- <% end %>
25
- <section aria-labelledby="additional-access-heading">
26
- <h2 id="additional-access-heading">Need additional access?</h2>
27
- <p>If your client cannot request write access, choose it here, then select Review access. You will review the updated access before authorizing.</p>
28
- <%= form_tag "#{SolidusMcp.configuration.endpoint_url}/oauth/authorize", method: :get, id: "review-oauth-scopes" do %>
29
- <%= hidden_field_tag :review_scopes, "1" %>
30
- <% %i[client_id redirect_uri state response_type code_challenge code_challenge_method resource].each do |key| %>
31
- <%= hidden_field_tag key, params[key], id: nil %>
32
- <% end %>
33
- <% scope_options.each do |scope| %>
34
- <p><label>
35
- <%= check_box_tag "requested_scopes[]", scope, @pre_auth.scopes.include?(scope), id: "oauth_scope_#{scope.tr(':', '_')}" %>
36
- <%= scope == "mcp:write" ? "Use enabled write tools, including tools enabled later" : "Use enabled read tools" %> (<code><%= scope %></code>)
37
- </label></p>
38
- <% end %>
39
- <%= submit_tag "Review access" %>
40
- <% end %>
41
- <p>Read and write access are separate; select both if you need both. Individual tools must still be enabled in AI connections. If write access is not listed, the client's registration must be updated before reconnecting.</p>
42
- </section>
43
- </main></body></html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Connect to your Solidus store</title>
7
+ <%= stylesheet_link_tag "solidus_mcp/admin", "solidus_mcp/consent" %>
8
+ </head>
9
+ <body class="solidus-mcp-consent">
10
+ <main class="solidus-mcp-admin solidus-mcp-consent-card" aria-labelledby="consent-heading">
11
+ <header>
12
+ <h1 id="consent-heading" class="solidus-mcp-page-title">Connect <%= @pre_auth.client.application.name %> to your Solidus store</h1>
13
+ <p>Only authorize an application you intended to connect. If someone sent you this link unexpectedly, deny the request.</p>
14
+ <p class="solidus-mcp-consent-address"><strong>Return address:</strong> <%= @pre_auth.redirect_uri %></p>
15
+ </header>
16
+ <div class="solidus-mcp-consent-access">
17
+ <% if @pre_auth.scopes.include?("mcp:read") %>
18
+ <section class="solidus-mcp-consent-scope">
19
+ <h2>Read access</h2>
20
+ <ul><li>Search products and variants.</li><li>View prices and inventory.</li><li>Read order information.</li></ul>
21
+ </section>
22
+ <% end %>
23
+ <% if @pre_auth.scopes.include?("mcp:write") %>
24
+ <section class="solidus-mcp-consent-scope">
25
+ <h2>Write access</h2>
26
+ <ul><li>Modify product information.</li><li>Update prices.</li><li>Perform other explicitly enabled store-management operations.</li></ul>
27
+ </section>
28
+ <% end %>
29
+ </div>
30
+ <p>Administrators must also enable individual tools in AI connections. They can change enabled tools within this access level without reconnecting.</p>
31
+ <div class="solidus-mcp-consent-actions">
32
+ <% {"Authorize" => :post, "Deny" => :delete}.each do |label, method| %>
33
+ <%= form_tag "#{SolidusMcp.configuration.endpoint_url}/oauth/authorize", method: method do %>
34
+ <% %i[client_id redirect_uri state response_type scope code_challenge code_challenge_method resource].each do |key| %>
35
+ <%= hidden_field_tag key, params[key], id: nil %>
36
+ <% end %>
37
+ <%= submit_tag label, class: "solidus-mcp-button#{' solidus-mcp-button-primary' if method == :post}" %>
38
+ <% end %>
39
+ <% end %>
40
+ </div>
41
+ <details class="solidus-mcp-consent-review">
42
+ <summary>Change requested access</summary>
43
+ <p>Need to use write tools? You can change the access requested for this connection. You’ll review your selection before approving.</p>
44
+ <%= form_tag "#{SolidusMcp.configuration.endpoint_url}/oauth/authorize", method: :get, id: "review-oauth-scopes" do %>
45
+ <%= hidden_field_tag :review_scopes, "1" %>
46
+ <% %i[client_id redirect_uri state response_type code_challenge code_challenge_method resource].each do |key| %>
47
+ <%= hidden_field_tag key, params[key], id: nil %>
48
+ <% end %>
49
+ <% scope_options.each do |scope| %>
50
+ <p><label class="solidus-mcp-consent-choice">
51
+ <%= check_box_tag "requested_scopes[]", scope, @pre_auth.scopes.include?(scope), id: "oauth_scope_#{scope.tr(':', '_')}" %>
52
+ <span><%= scope == "mcp:write" ? "Use enabled write tools, including tools enabled later" : "Use enabled read tools" %> (<code><%= scope %></code>)</span>
53
+ </label></p>
54
+ <% end %>
55
+ <%= submit_tag "Review access", class: "solidus-mcp-button" %>
56
+ <% end %>
57
+ <p>Read and write access are separate; select both if you need both. Individual tools must still be enabled in AI connections. If write access is not listed, the client's registration must be updated before reconnecting.</p>
58
+ </details>
59
+ </main>
60
+ </body>
61
+ </html>
data/config/routes.rb CHANGED
@@ -5,6 +5,7 @@ if defined?(SolidusAdmin::Engine)
5
5
  resources :mcp_administrators, only: [:index, :create, :update] do
6
6
  get :search, on: :collection
7
7
  end
8
+ resources :mcp_activity, only: [:index]
8
9
  resources :mcp_connections, only: [:index]
9
10
  get "mcp_connections/:id/owners/:user_id/edit", to: "mcp_connections#edit", as: :edit_mcp_connection
10
11
  patch "mcp_connections/:id/owners/:user_id", to: "mcp_connections#update", as: :mcp_connection
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateSolidusMcpStockAdjustments < ActiveRecord::Migration[7.2]
4
+ def change
5
+ create_table :solidus_mcp_stock_adjustments do |t|
6
+ t.references :connection_policy, null: false, foreign_key: {to_table: :solidus_mcp_connection_policies}, index: false
7
+ t.string :idempotency_key, null: false, limit: 128
8
+ t.bigint :variant_id, null: false
9
+ t.bigint :stock_location_id, null: false
10
+ t.integer :quantity, null: false
11
+ t.string :reason, null: false, limit: 1000
12
+ t.references :stock_movement, foreign_key: {to_table: :spree_stock_movements}
13
+ t.jsonb :result
14
+ t.timestamps
15
+ end
16
+ add_index :solidus_mcp_stock_adjustments, [:connection_policy_id, :idempotency_key],
17
+ unique: true, name: "index_mcp_stock_adjustments_on_request"
18
+ end
19
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateSolidusMcpToolRequests < ActiveRecord::Migration[7.2]
4
+ def change
5
+ create_table :solidus_mcp_tool_requests do |t|
6
+ t.references :connection_policy, null: false, foreign_key: {to_table: :solidus_mcp_connection_policies}, index: false
7
+ t.string :operation, null: false
8
+ t.string :idempotency_key, null: false, limit: 128
9
+ t.string :guard_key
10
+ t.jsonb :payload, null: false
11
+ t.string :status, null: false, default: "pending"
12
+ t.jsonb :result
13
+ t.timestamps
14
+ end
15
+ add_index :solidus_mcp_tool_requests, [:connection_policy_id, :operation, :idempotency_key], unique: true, name: "index_mcp_tool_requests_on_key"
16
+ add_index :solidus_mcp_tool_requests, :guard_key, unique: true,
17
+ where: "status IN ('processing', 'uncertain')", name: "index_mcp_tool_requests_on_active_target"
18
+ end
19
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateSolidusMcpActivityEvents < ActiveRecord::Migration[7.2]
4
+ def change
5
+ create_table :solidus_mcp_activity_events do |t|
6
+ # Preserve attribution when OAuth clients, tokens, or users are removed.
7
+ t.bigint :user_id
8
+ t.bigint :application_id
9
+ t.bigint :token_id
10
+ t.string :application_uid
11
+ t.string :application_name
12
+ t.string :event_id, null: false
13
+ t.string :request_id
14
+ t.string :protocol_method, null: false
15
+ t.string :tool_name
16
+ t.string :permission
17
+ t.string :category
18
+ t.string :action, null: false
19
+ t.string :status, null: false, default: "started"
20
+ t.jsonb :resource_ids, null: false, default: {}
21
+ t.jsonb :changed_fields, null: false, default: []
22
+ t.datetime :started_at, null: false
23
+ t.datetime :finished_at
24
+ t.bigint :duration_ms
25
+ t.string :error_class
26
+ end
27
+ add_index :solidus_mcp_activity_events, :event_id, unique: true
28
+ add_index :solidus_mcp_activity_events, :started_at
29
+ add_index :solidus_mcp_activity_events, [:user_id, :started_at]
30
+ add_index :solidus_mcp_activity_events, [:action, :started_at]
31
+ add_index :solidus_mcp_activity_events, [:tool_name, :started_at]
32
+ add_index :solidus_mcp_activity_events, [:status, :started_at]
33
+ end
34
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ class AddActorRoleToMcpActivityEvents < ActiveRecord::Migration[7.2]
4
+ def change
5
+ add_column :solidus_mcp_activity_events, :actor_role, :string, null: false, default: "unknown"
6
+ end
7
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ # Public SDK entry points cover schema rejection and undiscoverable tools,
5
+ # which never reach a tool's Ruby implementation.
6
+ class AuditedServer < MCP::Server
7
+ def initialize(credential:, **options)
8
+ @audit_credential = credential
9
+ super(**options)
10
+ end
11
+
12
+ def handle(payload, **options)
13
+ ActionAudit.protocol(credential: @audit_credential, payload: payload) { super }
14
+ end
15
+
16
+ def handle_json(payload, **options)
17
+ parsed = begin
18
+ JSON.parse(payload)
19
+ rescue JSON::ParserError
20
+ nil
21
+ end
22
+ ActionAudit.protocol(credential: @audit_credential, payload: parsed) { super }
23
+ end
24
+ end
25
+ end
@@ -5,7 +5,8 @@ require "uri"
5
5
  module SolidusMcp
6
6
  class Configuration
7
7
  attr_accessor :custom_tools, :endpoint_url, :issuer_url, :allowed_origins,
8
- :server_name, :instructions, :resource_owner_authenticator, :default_shipping_category_id, :superadmin_emails
8
+ :server_name, :instructions, :resource_owner_authenticator, :default_shipping_category_id, :superadmin_emails,
9
+ :product_serializer, :order_serializer
9
10
 
10
11
  def initialize
11
12
  @superadmin_emails = ENV.fetch("SOLIDUS_MCP_SUPERADMIN_EMAILS", "").split(",").map { |email| email.strip.downcase }.uniq
@@ -23,6 +24,23 @@ module SolidusMcp
23
24
  endpoint_url.present? && issuer_url.present?
24
25
  end
25
26
 
27
+ def serializer_class(kind)
28
+ name = public_send(:"#{kind}_serializer")
29
+ return if name.nil?
30
+ unless name.is_a?(String) && name.present?
31
+ raise ArgumentError, "#{kind}_serializer must be a class-name string or nil"
32
+ end
33
+ serializer = name.constantize
34
+ unless serializer.is_a?(Class) && serializer.respond_to?(:call)
35
+ raise ArgumentError, "#{name} must implement .call(record, context:)"
36
+ end
37
+ serializer
38
+ end
39
+
40
+ def validate_serializers!
41
+ %i[product order].each { |kind| serializer_class(kind) }
42
+ end
43
+
26
44
  def validate!
27
45
  [endpoint_url, issuer_url].each do |value|
28
46
  uri = URI.parse(value.to_s)