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,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
@@ -5,6 +5,7 @@ module SolidusMcp
5
5
  MAX_REQUEST_BYTES = 1.megabyte
6
6
 
7
7
  include HttpAccess
8
+ prepend_around_action :audit_request_context, except: :preflight
8
9
  before_action :authenticate, except: :preflight
9
10
 
10
11
  def handle
@@ -41,6 +42,35 @@ module SolidusMcp
41
42
 
42
43
  private
43
44
 
45
+ def audit_request_context
46
+ payload = nil
47
+ if request.post? && request.media_type == "application/json"
48
+ body = request.body.read(MAX_REQUEST_BYTES + 1)
49
+ request.body.rewind
50
+ payload = parse_payload(body) if body.bytesize <= MAX_REQUEST_BYTES
51
+ end
52
+ AuditContext.set(request_id: request.request_id, event_count: 0, invocation: nil) do
53
+ yield
54
+ ensure
55
+ # Authentication, scope challenges and transport checks can reject a
56
+ # request before SDK dispatch. Record these when identity is known.
57
+ if @audit_credential && payload.is_a?(Hash) && AuditContext.event_count.to_i.zero? && payload["method"].is_a?(String)
58
+ params = payload["params"].is_a?(Hash) ? payload["params"] : {}
59
+ method = payload["method"]
60
+ method = "unknown" unless %w[tools/call tools/list initialize ping].include?(method)
61
+ begin
62
+ ActionAudit.capture(credential: @audit_credential, protocol_method: method,
63
+ tool_name: params["name"], arguments: params["arguments"]) do |invocation|
64
+ invocation.status = [401, 403].include?(response.status) ? "denied" : "failed"
65
+ invocation.error_class = (invocation.status == "denied") ? "SolidusMcp::AccessDenied" : "MCP::ProtocolError"
66
+ end
67
+ rescue
68
+ Rails.logger.error("Solidus MCP could not record a rejected request")
69
+ end
70
+ end
71
+ end
72
+ end
73
+
44
74
  def parse_payload(body)
45
75
  JSON.parse(body)
46
76
  rescue JSON::ParserError
@@ -50,7 +80,13 @@ module SolidusMcp
50
80
  def authenticate
51
81
  bearer = request.authorization&.match(/\ABearer ([^\s]+)\z/i)&.captures&.first
52
82
  @credential = Credential.authenticate(bearer)
83
+ @audit_credential = @credential
53
84
  unless @credential
85
+ token = Doorkeeper::AccessToken.by_token(bearer) if bearer.present?
86
+ if token
87
+ owner = Spree.user_class.find_by(id: token.resource_owner_id)
88
+ @audit_credential = Credential.new(token, owner)
89
+ end
54
90
  response.set_header("WWW-Authenticate", %(Bearer resource_metadata="#{SolidusMcp.configuration.endpoint_url}/metadata"))
55
91
  return head :unauthorized
56
92
  end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ class ActivityEvent < ActiveRecord::Base
5
+ self.table_name = "solidus_mcp_activity_events"
6
+ ACTIONS = %w[read create update delete unknown].freeze
7
+ STATUSES = %w[started succeeded partial denied failed].freeze
8
+
9
+ validates :event_id, :protocol_method, :started_at, presence: true
10
+ validates :actor_role, inclusion: {in: %w[user admin superadmin unknown]}
11
+ validates :action, inclusion: {in: ACTIONS}
12
+ validates :status, inclusion: {in: STATUSES}
13
+
14
+ def self.visible_to(actor)
15
+ return none unless Administration.user?(actor)
16
+ return all if Administration.superadmin?(actor)
17
+ if Administration.administrator?(actor)
18
+ where(actor_role: "user").where.not(user_id: Administration.privileged_user_ids).or(where(user_id: actor.id))
19
+ else
20
+ where(user_id: actor.id)
21
+ end
22
+ end
23
+
24
+ # Identity, tool metadata and targets cannot be edited through model writes.
25
+ # The recorder completes a started event once through the narrow method below.
26
+ def readonly?
27
+ persisted?
28
+ end
29
+
30
+ def finish!(status:, duration_ms:, error_class: nil, result_ids: {})
31
+ raise ArgumentError, "Invalid final audit status" unless %w[succeeded partial denied failed].include?(status)
32
+ self.class.where(id: id, status: "started").update_all(status: status,
33
+ finished_at: Time.current, duration_ms: duration_ms, error_class: error_class,
34
+ resource_ids: resource_ids.merge(result_ids.empty? ? {} : {"result" => result_ids}))
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ class AuditContext < ActiveSupport::CurrentAttributes
5
+ attribute :invocation, :request_id, :event_count
6
+ end
7
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ # Keep these records for as long as requests can be retried. Deleting them
5
+ # removes the duplicate-request protection for their connection and key.
6
+ class StockAdjustment < ActiveRecord::Base
7
+ self.table_name = "solidus_mcp_stock_adjustments"
8
+
9
+ belongs_to :connection_policy, class_name: "SolidusMcp::ConnectionPolicy"
10
+ belongs_to :stock_movement, class_name: "Spree::StockMovement", optional: true
11
+
12
+ validates :idempotency_key, presence: true, length: {maximum: 128}
13
+ validates :reason, presence: true, length: {maximum: 1000}
14
+ validates :variant_id, :stock_location_id, :quantity, presence: true
15
+ end
16
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ class ToolRequest < ActiveRecord::Base
5
+ self.table_name = "solidus_mcp_tool_requests"
6
+ belongs_to :connection_policy, class_name: "SolidusMcp::ConnectionPolicy"
7
+ validates :operation, :idempotency_key, presence: true
8
+ validates :idempotency_key, length: {maximum: 128}
9
+ end
10
+ end
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ class ActionAudit
5
+ TARGET_KEYS = %w[product_id variant_id price_id order_id payment_id shipment_id
6
+ taxon_id taxonomy_id option_type_id option_value_id shipping_category_id
7
+ stock_location_id stock_item_id image_id image_ids refund_reason_id refund_id stock_movement_id].freeze
8
+ Invocation = Struct.new(:event, :credential, :tool_name, :claimed, :status, :error_class, :result_ids, keyword_init: true)
9
+
10
+ class << self
11
+ def tool(credential:, tool_name:, arguments:)
12
+ invocation = AuditContext.invocation
13
+ if invocation && !invocation.claimed && invocation.tool_name == tool_name && invocation.credential.equal?(credential)
14
+ invocation.claimed = true
15
+ observe(invocation) do
16
+ result = yield
17
+ summarize_result(invocation, result)
18
+ result
19
+ end
20
+ else
21
+ capture(credential: credential, tool_name: tool_name, arguments: arguments, protocol_method: "tools/call") do |current|
22
+ current.claimed = true
23
+ result = yield
24
+ summarize_result(current, result)
25
+ result
26
+ end
27
+ end
28
+ end
29
+
30
+ def protocol(credential:, payload:)
31
+ return yield unless payload.is_a?(Hash)
32
+ method = payload[:method] || payload["method"]
33
+ return yield unless method.is_a?(String)
34
+ params = payload[:params] || payload["params"]
35
+ params = {} unless params.is_a?(Hash)
36
+ tool_name = params[:name] || params["name"] if method == "tools/call"
37
+ arguments = params[:arguments] || params["arguments"]
38
+ # Only named protocol operations are retained, never arbitrary client text.
39
+ method = "unknown" unless %w[initialize ping tools/call tools/list resources/list resources/read resources/templates/list prompts/list prompts/get notifications/initialized].include?(method)
40
+ capture(credential: credential, tool_name: tool_name, arguments: arguments, protocol_method: method) do |invocation|
41
+ result = yield
42
+ response = result.is_a?(String) ? JSON.parse(result) : result
43
+ if protocol_method_tool_notification?(method, invocation, response)
44
+ invocation.status = "failed"
45
+ invocation.error_class = "MCP::ProtocolError"
46
+ end
47
+ response_result = response["result"] || response[:result] if response.is_a?(Hash)
48
+ error_result = response_result.is_a?(Hash) && (response_result["isError"] || response_result[:isError])
49
+ if response.is_a?(Hash) && (response.key?("error") || response.key?(:error) || error_result)
50
+ unless invocation.status
51
+ entry = SolidusMcp.registry.tools[tool_name] if tool_name.is_a?(String)
52
+ allowed = entry && Policy.new(credential).allowed?(entry)
53
+ invocation.status = (method == "tools/call" && !allowed) ? "denied" : "failed"
54
+ invocation.error_class = allowed ? "MCP::ProtocolError" : "SolidusMcp::AccessDenied"
55
+ end
56
+ end
57
+ result
58
+ end
59
+ end
60
+
61
+ def capture(credential:, tool_name:, arguments:, protocol_method:)
62
+ entry = SolidusMcp.registry.tools[tool_name] if tool_name.is_a?(String)
63
+ args = arguments.is_a?(Hash) ? arguments.stringify_keys : {}
64
+ token = credential.token
65
+ application = token.application
66
+ fields = args["changes"].is_a?(Hash) ? args["changes"].keys.map(&:to_s) : []
67
+ allowed_fields = entry&.input_schema&.dig(:properties, "changes", :properties)&.keys || []
68
+ event = ActivityEvent.create!(event_id: SecureRandom.uuid, request_id: AuditContext.request_id,
69
+ user_id: token.resource_owner_id, actor_role: Administration.role(credential.user)&.to_s || "unknown", application_id: token.application_id, token_id: token.id,
70
+ application_uid: application&.uid, application_name: application&.name&.first(255),
71
+ protocol_method: protocol_method, tool_name: entry&.name || ((protocol_method == "tools/call") ? "[unknown tool]" : nil),
72
+ permission: entry&.permission, category: entry&.category || "Protocol",
73
+ action: entry&.audit_action || ((protocol_method == "tools/call") ? "unknown" : "read"),
74
+ resource_ids: target_ids(args), changed_fields: (fields & allowed_fields.map(&:to_s)).sort,
75
+ started_at: Time.current)
76
+ AuditContext.event_count = AuditContext.event_count.to_i + 1
77
+ invocation = Invocation.new(event: event, credential: credential, tool_name: tool_name, claimed: false)
78
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
79
+ previous = AuditContext.invocation
80
+ AuditContext.invocation = invocation
81
+ finished_normally = false
82
+ begin
83
+ result = observe(invocation) { yield invocation }
84
+ finished_normally = true
85
+ result
86
+ ensure
87
+ AuditContext.invocation = previous
88
+ elapsed = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
89
+ begin
90
+ if finished_normally || invocation.status
91
+ event.finish!(status: invocation.status || "succeeded", duration_ms: elapsed, error_class: invocation.error_class, result_ids: invocation.result_ids || {})
92
+ end
93
+ rescue
94
+ # The initial record remains visible as unfinished. Do not turn an
95
+ # already-completed mutation into a failure and invite a duplicate retry.
96
+ Rails.logger.error("Solidus MCP could not complete activity event #{event.event_id}")
97
+ end
98
+ end
99
+ end
100
+
101
+ private
102
+
103
+ def observe(invocation)
104
+ yield
105
+ rescue => error
106
+ invocation.status = error.is_a?(SolidusMcp::AccessDenied) ? "denied" : "failed"
107
+ invocation.error_class = error.class.name.presence || "StandardError"
108
+ raise
109
+ end
110
+
111
+ def protocol_method_tool_notification?(method, invocation, response)
112
+ method == "tools/call" && !invocation.claimed && response.nil?
113
+ end
114
+
115
+ def summarize_result(invocation, result)
116
+ invocation.result_ids = result_ids(result)
117
+ return unless result.is_a?(Hash)
118
+ batch = result[:results] || result["results"]
119
+ return unless batch.is_a?(Array) && batch.any?
120
+ flags = batch.first(100).map do |item|
121
+ next :unknown unless item.is_a?(Hash)
122
+ value = item.key?(:success) ? item[:success] : item["success"]
123
+ (value == true || value == false) ? value : :unknown
124
+ end
125
+ return unless flags.size == batch.size && !flags.include?(:unknown)
126
+ invocation.status = if flags.all?
127
+ "succeeded"
128
+ else
129
+ (flags.any? ? "partial" : "failed")
130
+ end
131
+ end
132
+
133
+ def result_ids(result)
134
+ return {} unless result.is_a?(Hash)
135
+ values = result.stringify_keys
136
+ ids = target_ids(values)
137
+ records = values["items"].is_a?(Array) ? values["items"].first(100) : [values]
138
+ returned = records.filter_map do |record|
139
+ next unless record.is_a?(Hash)
140
+ id = record[:id] || record["id"]
141
+ id if id.is_a?(Integer) && id.positive?
142
+ end
143
+ ids["returned_ids"] = returned unless returned.empty?
144
+ if values["results"].is_a?(Array)
145
+ ids["batch"] = values["results"].first(100).filter_map do |record|
146
+ next unless record.is_a?(Hash)
147
+ item = record.stringify_keys
148
+ next unless [true, false].include?(item["success"])
149
+ references = item["price"].is_a?(Hash) ? target_ids(item["price"].stringify_keys) : {}
150
+ references.merge("success" => item["success"]).tap do |entry|
151
+ entry["index"] = item["index"] if item["index"].is_a?(Integer) && item["index"] >= 0
152
+ end
153
+ end
154
+ end
155
+ ids
156
+ end
157
+
158
+ def target_ids(arguments)
159
+ arguments.slice(*TARGET_KEYS).filter_map do |key, value|
160
+ if value.is_a?(Integer) && value.positive?
161
+ [key, value]
162
+ elsif value.is_a?(Array) && value.length <= 100 && value.all? { |id| id.is_a?(Integer) && id.positive? }
163
+ [key, value]
164
+ end
165
+ end.to_h
166
+ end
167
+ end
168
+ end
169
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ class ImageContext
5
+ attr_reader :product, :variant
6
+
7
+ def initialize(policy, product_id:, variant_id: nil, action: :read)
8
+ @policy, @action = policy, action
9
+ @product = policy.scope(Spree::Product, action).find(product_id)
10
+ id = variant_id || @product.master.id
11
+ @variant = policy.scope(Spree::Variant, action).where(product_id: product_id).find(id)
12
+ authorize!
13
+ end
14
+
15
+ def authorize!
16
+ @policy.authorize_record!(@action, product)
17
+ @policy.authorize_record!(@action, variant)
18
+ end
19
+
20
+ def with_lock
21
+ product.with_lock do
22
+ variant.with_lock do
23
+ authorize!
24
+ yield
25
+ end
26
+ end
27
+ end
28
+
29
+ def images(action = :read)
30
+ @policy.scope(Spree::Image, action).where(viewable: variant)
31
+ end
32
+
33
+ def metadata(image)
34
+ result = {id: image.id, product_id: product.id, variant_id: variant.id,
35
+ position: image.position, alt: image.alt}
36
+ if image.class.reflect_on_association(:attachment_attachment)
37
+ blob = image.attachment.blob
38
+ result[:content_type] = blob&.content_type
39
+ result[:byte_size] = blob&.byte_size
40
+ end
41
+ result
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidusMcp
4
+ class OrderWorkflowAuthorization
5
+ def initialize(policy)
6
+ @policy = policy
7
+ end
8
+
9
+ def shipping(shipment, tracking: shipment.tracking, notify_customer: true)
10
+ @policy.authorize_record!(:update, shipment.order)
11
+ @policy.authorize_record!(:ship, shipment)
12
+ @policy.authorize_record!(:read, shipment.stock_location)
13
+ @policy.authorize_record!(:read, shipment.order.ship_address)
14
+ @policy.authorize_record!(:read, shipment.shipping_method)
15
+ shipment.inventory_units.each do |unit|
16
+ @policy.authorize_record!(:update, unit)
17
+ @policy.authorize_record!(:read, unit.variant)
18
+ @policy.authorize_record!(:read, unit.variant.product)
19
+ end
20
+ carton = Spree::Carton.new(stock_location_id: shipment.stock_location_id, address_id: shipment.order.ship_address_id,
21
+ shipping_method_id: shipment.shipping_method&.id, shipped_at: Time.current,
22
+ tracking: tracking, suppress_email: !notify_customer)
23
+ # Set the authorization preview's collection without assigning inverse
24
+ # carton links to live inventory units before the real workflow runs.
25
+ carton.association(:inventory_units).target = shipment.inventory_units.select(&:on_hand?)
26
+ @policy.authorize_record!(:create, carton)
27
+ end
28
+
29
+ def cancellation(order)
30
+ @policy.authorize_record!(:cancel, order)
31
+ order.shipments.each do |shipment|
32
+ @policy.authorize_record!(:cancel, shipment)
33
+ @policy.authorize_record!(:read, shipment.stock_location)
34
+ shipment.inventory_units.each do |unit|
35
+ @policy.authorize_record!(:update, unit)
36
+ @policy.authorize_record!(:read, unit.variant)
37
+ @policy.authorize_record!(:read, unit.variant.product)
38
+ end
39
+ Spree::ShippingManifest.new(inventory_units: shipment.inventory_units).items.each do |manifest|
40
+ item = Spree::StockItem.find_by!(variant_id: manifest.variant.id, stock_location_id: shipment.stock_location_id)
41
+ on_hand = manifest.states["on_hand"].to_i
42
+ backordered = manifest.states["backordered"].to_i
43
+ next if on_hand.zero? && backordered.zero?
44
+ @policy.authorize_record!(:update, item, attribute: :count_on_hand)
45
+ if on_hand.positive?
46
+ @policy.authorize_record!(:create, Spree::StockMovement.new(stock_item_id: item.id, quantity: on_hand, originator: shipment))
47
+ item.backordered_inventory_units.limit(on_hand).each do |backorder|
48
+ @policy.authorize_record!(:update, backorder)
49
+ @policy.authorize_record!(:update, backorder.order)
50
+ end
51
+ end
52
+ original_count = item.count_on_hand
53
+ begin
54
+ item[:count_on_hand] += backordered + (item.should_track_inventory? ? on_hand : 0)
55
+ @policy.authorize_record!(:update, item, attribute: :count_on_hand)
56
+ ensure
57
+ item[:count_on_hand] = original_count
58
+ end
59
+ end
60
+ end
61
+ order.payments.each do |payment|
62
+ next if payment.fully_refunded? || !(payment.pending? || payment.completed?)
63
+ @policy.authorize_record!(:update, payment)
64
+ @policy.authorize_record!(:cancel, payment)
65
+ reason = Spree::RefundReason.find_by(name: Spree::Payment::Cancellation::DEFAULT_REASON)
66
+ if reason
67
+ @policy.authorize_record!(:read, reason)
68
+ else
69
+ reason = Spree::RefundReason.new(name: Spree::Payment::Cancellation::DEFAULT_REASON)
70
+ @policy.authorize_record!(:create, reason)
71
+ end
72
+ @policy.authorize_record!(:create, Spree::Refund.new(payment_id: payment.id, reason: reason, amount: payment.credit_allowed))
73
+ end
74
+ end
75
+ end
76
+ end
@@ -1,7 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SolidusMcp
4
- # Fixed public representations. Related records are checked separately.
4
+ # Record authorization stays outside host serialization. Custom serializers are
5
+ # trusted application code and must authorize any related records they expose.
5
6
  class Serializers
6
7
  def initialize(policy)
7
8
  @policy = policy
@@ -9,7 +10,9 @@ module SolidusMcp
9
10
 
10
11
  def product(record)
11
12
  @policy.authorize_record!(:read, record)
12
- record.attributes.slice("id", "name", "slug", "description", "meta_title", "meta_description", "meta_keywords")
13
+ serialize(:product, record) do
14
+ record.attributes.slice("id", "name", "slug", "description", "meta_title", "meta_description", "meta_keywords")
15
+ end
13
16
  end
14
17
 
15
18
  def variant(record)
@@ -36,8 +39,10 @@ module SolidusMcp
36
39
 
37
40
  def order(record)
38
41
  @policy.authorize_record!(:read, record)
39
- status(record).merge(currency: record.currency, total: record.total.to_s("F"),
40
- item_total: record.item_total.to_s("F"), completed_at: record.completed_at&.iso8601)
42
+ serialize(:order, record) do
43
+ status(record).merge(currency: record.currency, total: record.total.to_s("F"),
44
+ item_total: record.item_total.to_s("F"), completed_at: record.completed_at&.iso8601)
45
+ end
41
46
  end
42
47
 
43
48
  def status(record)
@@ -45,5 +50,24 @@ module SolidusMcp
45
50
  {id: record.id, number: record.number, state: record.state,
46
51
  payment_state: record.payment_state, shipment_state: record.shipment_state}
47
52
  end
53
+
54
+ private
55
+
56
+ def serialize(kind, record)
57
+ serializer = SolidusMcp.configuration.serializer_class(kind)
58
+ return yield unless serializer
59
+
60
+ result = serializer.call(record, context: @policy)
61
+ valid = result.is_a?(Hash) && result.keys.all? { |key| key.is_a?(String) || key.is_a?(Symbol) }
62
+ unless valid
63
+ raise ToolError, "#{serializer.name} must return a Hash with string or symbol keys, not encoded JSON"
64
+ end
65
+ keys = result.keys.map(&:to_s)
66
+ raise ToolError, "#{serializer.name} returned duplicate field names" unless keys.uniq == keys
67
+ if kind == :order && (keys & %w[line_items line_items_truncated]).any?
68
+ raise ToolError, "Order serializers cannot replace line_items or line_items_truncated"
69
+ end
70
+ result.dup
71
+ end
48
72
  end
49
73
  end