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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +63 -0
- data/README.md +321 -3
- data/app/assets/stylesheets/solidus_mcp/admin.css +39 -0
- data/app/assets/stylesheets/solidus_mcp/consent.css +77 -0
- data/app/controllers/solidus_admin/mcp_activity_controller.rb +67 -0
- data/app/controllers/solidus_mcp/endpoint_controller.rb +36 -0
- data/app/models/solidus_mcp/activity_event.rb +37 -0
- data/app/models/solidus_mcp/audit_context.rb +7 -0
- data/app/models/solidus_mcp/stock_adjustment.rb +16 -0
- data/app/models/solidus_mcp/tool_request.rb +10 -0
- data/app/services/solidus_mcp/action_audit.rb +169 -0
- data/app/services/solidus_mcp/image_context.rb +44 -0
- data/app/services/solidus_mcp/order_workflow_authorization.rb +76 -0
- data/app/services/solidus_mcp/tool_request_execution.rb +76 -0
- data/app/tools/solidus_mcp/tools/add_product_option_type.rb +36 -0
- data/app/tools/solidus_mcp/tools/add_product_to_taxon.rb +40 -0
- data/app/tools/solidus_mcp/tools/adjust_stock.rb +98 -0
- data/app/tools/solidus_mcp/tools/attach_product_image.rb +77 -0
- data/app/tools/solidus_mcp/tools/bulk_update_variant_prices.rb +1 -1
- data/app/tools/solidus_mcp/tools/cancel_order.rb +44 -0
- data/app/tools/solidus_mcp/tools/create_product.rb +1 -0
- data/app/tools/solidus_mcp/tools/create_variant_price.rb +59 -0
- data/app/tools/solidus_mcp/tools/list_option_types.rb +34 -0
- data/app/tools/solidus_mcp/tools/list_option_values.rb +27 -0
- data/app/tools/solidus_mcp/tools/list_product_images.rb +26 -0
- data/app/tools/solidus_mcp/tools/list_shipping_categories.rb +24 -0
- data/app/tools/solidus_mcp/tools/list_stock_locations.rb +27 -0
- data/app/tools/solidus_mcp/tools/list_taxons.rb +40 -0
- data/app/tools/solidus_mcp/tools/publish_product.rb +32 -0
- data/app/tools/solidus_mcp/tools/refund_payment.rb +63 -0
- data/app/tools/solidus_mcp/tools/remove_product_image.rb +33 -0
- data/app/tools/solidus_mcp/tools/reorder_product_images.rb +41 -0
- data/app/tools/solidus_mcp/tools/ship_shipment.rb +63 -0
- data/app/tools/solidus_mcp/tools/unpublish_product.rb +29 -0
- data/app/tools/solidus_mcp/tools/update_variant.rb +54 -0
- data/app/tools/solidus_mcp/tools/update_variant_price.rb +1 -1
- data/app/views/solidus_admin/mcp_activity/index.html.erb +53 -0
- data/app/views/solidus_admin/mcp_connections/index.html.erb +2 -0
- data/app/views/solidus_mcp/authorizations/new.html.erb +59 -41
- data/config/routes.rb +1 -0
- data/db/migrate/20261112000000_create_solidus_mcp_stock_adjustments.rb +19 -0
- data/db/migrate/20261112010000_create_solidus_mcp_tool_requests.rb +19 -0
- data/db/migrate/20261112020000_create_solidus_mcp_activity_events.rb +34 -0
- data/db/migrate/20261112020100_add_actor_role_to_mcp_activity_events.rb +7 -0
- data/lib/solidus_mcp/audited_server.rb +25 -0
- data/lib/solidus_mcp/engine.rb +8 -3
- data/lib/solidus_mcp/policy.rb +4 -4
- data/lib/solidus_mcp/registry.rb +5 -2
- data/lib/solidus_mcp/server.rb +1 -2
- data/lib/solidus_mcp/tool.rb +9 -7
- data/lib/solidus_mcp/version.rb +1 -1
- data/lib/solidus_mcp.rb +5 -1
- metadata +37 -2
|
@@ -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,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
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SolidusMcp
|
|
4
|
+
# External effects cannot be undone by a database rollback. Commit the claim
|
|
5
|
+
# before entering the workflow and keep uncertain targets blocked for review.
|
|
6
|
+
class ToolRequestExecution
|
|
7
|
+
def initialize(credential, operation:, key:, payload:)
|
|
8
|
+
unless key.match?(/\A[A-Za-z0-9_.:-]{1,128}\z/)
|
|
9
|
+
raise ToolError, "Invalid idempotency key"
|
|
10
|
+
end
|
|
11
|
+
@connection = ConnectionPolicy.find_by!(application_id: credential.token.application_id, user_id: credential.user.id)
|
|
12
|
+
@operation, @key, @payload = operation, key, payload.deep_stringify_keys
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def database
|
|
16
|
+
ToolRequest.transaction do
|
|
17
|
+
request = find_request
|
|
18
|
+
request.with_lock do
|
|
19
|
+
check_payload!(request)
|
|
20
|
+
return request.result.symbolize_keys if request.status == "succeeded"
|
|
21
|
+
result = yield
|
|
22
|
+
request.update!(status: "succeeded", result: result)
|
|
23
|
+
result
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def external(guard_key:)
|
|
29
|
+
if ToolRequest.connection.transaction_open?
|
|
30
|
+
raise ToolError, "External workflow tools must run outside an enclosing database transaction"
|
|
31
|
+
end
|
|
32
|
+
request = find_request
|
|
33
|
+
replay = nil
|
|
34
|
+
request.with_lock do
|
|
35
|
+
check_payload!(request)
|
|
36
|
+
if request.status == "succeeded"
|
|
37
|
+
replay = request.result.symbolize_keys
|
|
38
|
+
elsif %w[processing uncertain].include?(request.status)
|
|
39
|
+
raise ToolError, "Request #{request.id} requires reconciliation before retry"
|
|
40
|
+
else
|
|
41
|
+
request.update!(status: "processing", guard_key: guard_key)
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
return replay if replay
|
|
45
|
+
|
|
46
|
+
effects_started = false
|
|
47
|
+
begin
|
|
48
|
+
ToolRequest.transaction do
|
|
49
|
+
result = yield(-> { effects_started = true })
|
|
50
|
+
request.update!(status: "succeeded", result: result)
|
|
51
|
+
result
|
|
52
|
+
end
|
|
53
|
+
rescue
|
|
54
|
+
request.reload.update!(status: effects_started ? "uncertain" : "failed")
|
|
55
|
+
if effects_started
|
|
56
|
+
raise ToolError, "Request #{request.id} may have reached external systems; reconcile before retry. No automatic repeat is allowed."
|
|
57
|
+
end
|
|
58
|
+
raise
|
|
59
|
+
end
|
|
60
|
+
rescue ActiveRecord::RecordNotUnique
|
|
61
|
+
raise ToolError, "Another unresolved operation exists for this order; reconcile it before retry"
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
private
|
|
65
|
+
|
|
66
|
+
def find_request
|
|
67
|
+
ToolRequest.create_or_find_by!(connection_policy_id: @connection.id, operation: @operation, idempotency_key: @key) do |record|
|
|
68
|
+
record.payload = @payload
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def check_payload!(request)
|
|
73
|
+
raise ToolError, "Idempotency key was already used with different inputs" unless request.payload == @payload
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SolidusMcp
|
|
4
|
+
module Tools
|
|
5
|
+
class AddProductOptionType < Base
|
|
6
|
+
tool_name :add_product_option_type
|
|
7
|
+
description "Attach an existing option type to a product, preserving existing options and variants. Repeated calls are safe."
|
|
8
|
+
category "Products"
|
|
9
|
+
permission "add_product_option_type"
|
|
10
|
+
read_only false
|
|
11
|
+
audit_action "create"
|
|
12
|
+
ability :update, "Spree::Product"
|
|
13
|
+
ability :read, "Spree::OptionType"
|
|
14
|
+
ability :create, "Spree::ProductOptionType"
|
|
15
|
+
input :product_id, type: "integer", minimum: 1, required: true
|
|
16
|
+
input :option_type_id, type: "integer", minimum: 1, required: true
|
|
17
|
+
|
|
18
|
+
protected
|
|
19
|
+
|
|
20
|
+
def call(product_id:, option_type_id:)
|
|
21
|
+
product = policy.scope(Spree::Product, :update).find(product_id)
|
|
22
|
+
product.with_lock do
|
|
23
|
+
authorize!
|
|
24
|
+
policy.authorize_record!(:update, product)
|
|
25
|
+
option_type = policy.authorize_record!(:read, policy.scope(Spree::OptionType).find(option_type_id))
|
|
26
|
+
unless product.product_option_types.exists?(option_type_id: option_type.id)
|
|
27
|
+
attachment = product.product_option_types.build(option_type: option_type)
|
|
28
|
+
policy.authorize_record!(:create, attachment)
|
|
29
|
+
attachment.save!
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
{product_id: product.id, option_type_id: option_type_id, attached: true}
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SolidusMcp
|
|
4
|
+
module Tools
|
|
5
|
+
class AddProductToTaxon < Base
|
|
6
|
+
tool_name :add_product_to_taxon
|
|
7
|
+
description "Add a product to an existing taxon without replacing its other categories. New classifications append to the taxon's product ordering; repeated calls preserve existing positions."
|
|
8
|
+
category "Products"
|
|
9
|
+
permission "add_product_to_taxon"
|
|
10
|
+
read_only false
|
|
11
|
+
audit_action "create"
|
|
12
|
+
ability :update, "Spree::Product"
|
|
13
|
+
ability :read, "Spree::Taxon"
|
|
14
|
+
ability :create, "Spree::Classification"
|
|
15
|
+
input :product_id, type: "integer", minimum: 1, required: true
|
|
16
|
+
input :taxon_id, type: "integer", minimum: 1, required: true
|
|
17
|
+
|
|
18
|
+
protected
|
|
19
|
+
|
|
20
|
+
def call(product_id:, taxon_id:)
|
|
21
|
+
product = policy.scope(Spree::Product, :update).find(product_id)
|
|
22
|
+
product.with_lock do
|
|
23
|
+
taxon = policy.scope(Spree::Taxon).find(taxon_id)
|
|
24
|
+
taxon.with_lock do
|
|
25
|
+
authorize!
|
|
26
|
+
policy.authorize_record!(:update, product)
|
|
27
|
+
policy.authorize_record!(:update, product, attribute: :taxon_ids)
|
|
28
|
+
policy.authorize_record!(:read, taxon)
|
|
29
|
+
unless product.classifications.exists?(taxon_id: taxon.id)
|
|
30
|
+
classification = product.classifications.build(taxon: taxon)
|
|
31
|
+
policy.authorize_record!(:create, classification)
|
|
32
|
+
classification.save!
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
{product_id: product.id, taxon_id: taxon_id, attached: true}
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SolidusMcp
|
|
4
|
+
module Tools
|
|
5
|
+
class AdjustStock < Base
|
|
6
|
+
tool_name :adjust_stock
|
|
7
|
+
description "Apply a signed stock movement to an existing variant/location stock item. Requires a reason and a connection-scoped idempotency key; retry with identical inputs. Solidus validations and backorder processing apply."
|
|
8
|
+
category "Inventory"
|
|
9
|
+
permission "adjust_stock"
|
|
10
|
+
read_only false
|
|
11
|
+
ability :read, "Spree::Product"
|
|
12
|
+
ability :read, "Spree::Variant"
|
|
13
|
+
ability :read, "Spree::StockLocation"
|
|
14
|
+
ability :update, "Spree::StockItem"
|
|
15
|
+
ability :create, "Spree::StockMovement"
|
|
16
|
+
input :variant_id, type: "integer", minimum: 1, required: true
|
|
17
|
+
input :stock_location_id, type: "integer", minimum: 1, required: true
|
|
18
|
+
input :quantity, type: "integer", minimum: -2147483647, maximum: 2147483647,
|
|
19
|
+
not: {const: 0}, required: true
|
|
20
|
+
input :reason, type: "string", minLength: 1, maxLength: 1000, required: true
|
|
21
|
+
input :idempotency_key, type: "string", minLength: 1, maxLength: 128,
|
|
22
|
+
pattern: "^[A-Za-z0-9_.:-]+$", required: true
|
|
23
|
+
|
|
24
|
+
protected
|
|
25
|
+
|
|
26
|
+
def call(variant_id:, stock_location_id:, quantity:, reason:, idempotency_key:)
|
|
27
|
+
raise ToolError, "Reason must not be blank" if reason.strip.empty?
|
|
28
|
+
unless idempotency_key.match?(/\A[A-Za-z0-9_.:-]+\z/)
|
|
29
|
+
raise ToolError, "Invalid idempotency key"
|
|
30
|
+
end
|
|
31
|
+
connection = ConnectionPolicy.find_by!(application_id: credential.token.application_id, user_id: credential.user.id)
|
|
32
|
+
request = {variant_id: variant_id, stock_location_id: stock_location_id, quantity: quantity, reason: reason}
|
|
33
|
+
StockAdjustment.transaction do
|
|
34
|
+
# The database unique index serializes first use of a key across
|
|
35
|
+
# processes. Failed movements roll back this row as well as the stock.
|
|
36
|
+
adjustment = StockAdjustment.create_or_find_by!(connection_policy_id: connection.id, idempotency_key: idempotency_key) do |record|
|
|
37
|
+
record.assign_attributes(request)
|
|
38
|
+
end
|
|
39
|
+
adjustment.with_lock do
|
|
40
|
+
authorize!
|
|
41
|
+
unless adjustment.attributes.symbolize_keys.slice(*request.keys) == request
|
|
42
|
+
raise ToolError, "Idempotency key was already used with different inputs"
|
|
43
|
+
end
|
|
44
|
+
item = policy.scope(Spree::StockItem, :update)
|
|
45
|
+
.where(variant_id: variants.where(id: variant_id).select(:id),
|
|
46
|
+
stock_location_id: policy.scope(Spree::StockLocation).where(id: stock_location_id).select(:id)).sole
|
|
47
|
+
item.with_lock do
|
|
48
|
+
unless item.variant_id == variant_id && item.stock_location_id == stock_location_id
|
|
49
|
+
raise ToolError, "Stock item context changed; retrieve inventory again"
|
|
50
|
+
end
|
|
51
|
+
if adjustment.result && adjustment.result["stock_item_id"] != item.id
|
|
52
|
+
raise ToolError, "Stock item was replaced after this request completed"
|
|
53
|
+
end
|
|
54
|
+
# Match Solidus's stock-item -> variant lock order. Keep inventory
|
|
55
|
+
# tracking stable while the movement callback runs.
|
|
56
|
+
item.variant.with_lock do
|
|
57
|
+
authorize!
|
|
58
|
+
authorize_stock!(item)
|
|
59
|
+
movement = Spree::StockMovement.new(stock_item: item, quantity: quantity, originator: adjustment)
|
|
60
|
+
policy.authorize_record!(:create, movement)
|
|
61
|
+
unless adjustment.result
|
|
62
|
+
unless item.should_track_inventory?
|
|
63
|
+
raise ToolError, "Inventory tracking must be enabled for this variant and store"
|
|
64
|
+
end
|
|
65
|
+
unless item.stock_location.active?
|
|
66
|
+
raise ToolError, "Stock location must be active"
|
|
67
|
+
end
|
|
68
|
+
before = item.count_on_hand
|
|
69
|
+
unless (before + quantity).between?(-2147483648, 2147483647)
|
|
70
|
+
raise ToolError, "Resulting stock count exceeds the supported integer range"
|
|
71
|
+
end
|
|
72
|
+
movement.save!
|
|
73
|
+
item.reload
|
|
74
|
+
authorize_stock!(item)
|
|
75
|
+
adjustment.update!(stock_movement: movement, result: {
|
|
76
|
+
stock_movement_id: movement.id, stock_item_id: item.id,
|
|
77
|
+
variant_id: variant_id, stock_location_id: stock_location_id,
|
|
78
|
+
quantity: quantity, count_on_hand_before: before,
|
|
79
|
+
count_on_hand_after: item.count_on_hand
|
|
80
|
+
})
|
|
81
|
+
end
|
|
82
|
+
adjustment.result.symbolize_keys
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def authorize_stock!(item)
|
|
90
|
+
policy.authorize_record!(:read, item.variant.product)
|
|
91
|
+
policy.authorize_record!(:read, item.variant)
|
|
92
|
+
policy.authorize_record!(:read, item.stock_location)
|
|
93
|
+
policy.authorize_record!(:update, item)
|
|
94
|
+
policy.authorize_record!(:update, item, attribute: :count_on_hand)
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
end
|