administrate-mcp 0.3.1 → 0.5.0
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 +68 -1
- data/README.md +17 -3
- data/app/lib/administrate/mcp/action_result.rb +36 -0
- data/app/lib/administrate/mcp/actions/result_data.rb +96 -0
- data/app/lib/administrate/mcp/actions.rb +87 -36
- data/app/lib/administrate/mcp/base_tool.rb +14 -5
- data/app/lib/administrate/mcp/clean_expired_upload_batches.rb +27 -0
- data/app/lib/administrate/mcp/field_serializer.rb +4 -0
- data/app/lib/administrate/mcp/server_builder.rb +7 -1
- data/app/lib/administrate/mcp/tools/uploads_prepare.rb +48 -0
- data/app/lib/administrate/mcp/uploads/declarations.rb +106 -0
- data/app/lib/administrate/mcp/uploads/shrine_storage.rb +77 -0
- data/app/lib/administrate/mcp/uploads.rb +135 -0
- data/app/models/administrate/mcp/upload_batch.rb +29 -0
- data/db/migrate/20260101000004_create_administrate_model_context_protocol_upload_batches.rb +18 -0
- data/docs/configuration.md +4 -0
- data/docs/dashboards.md +93 -4
- data/docs/development.md +5 -2
- data/docs/uploads.md +157 -0
- data/lib/administrate/mcp/configuration.rb +5 -1
- data/lib/administrate/mcp/uploads_configuration.rb +51 -0
- data/lib/administrate/mcp/version.rb +1 -1
- metadata +12 -1
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Administrate
|
|
4
|
+
module MCP
|
|
5
|
+
module Uploads
|
|
6
|
+
# How an `mcp_action` declares uploads: which attachment attributes take an
|
|
7
|
+
# `<attribute>_upload_id`, the schema of those params, and turning them into attachment
|
|
8
|
+
# values before the action's block runs.
|
|
9
|
+
module Declarations
|
|
10
|
+
RULE_KEYS = %i[content_types max_size].freeze
|
|
11
|
+
|
|
12
|
+
class << self
|
|
13
|
+
def normalize(uploads, action_name:)
|
|
14
|
+
return true if uploads == true
|
|
15
|
+
return {} unless uploads
|
|
16
|
+
return Array(uploads).to_h { |attribute| [attribute.to_sym, {}] } unless uploads.is_a?(Hash)
|
|
17
|
+
|
|
18
|
+
uploads.to_h do |attribute, rules|
|
|
19
|
+
[attribute.to_sym, validate_rules!("#{action_name}: uploads: #{attribute}", rules)]
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def any?(action_tools)
|
|
24
|
+
config.enabled && action_tools.any? { |tool| tool.definition.uploads.any? }
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def action_attributes(dashboard_class, action_name, declared)
|
|
28
|
+
return {} if declared.blank? || !config.enabled
|
|
29
|
+
|
|
30
|
+
attachments = attachment_attributes(dashboard_class)
|
|
31
|
+
if declared == true
|
|
32
|
+
return attachments.index_with({}) if attachments.any?
|
|
33
|
+
|
|
34
|
+
raise ArgumentError, "#{dashboard_class.name} #{action_name}: uploads: true, but the dashboard has " \
|
|
35
|
+
'no attachment attribute'
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
unknown = declared.keys - attachments
|
|
39
|
+
return declared if unknown.empty?
|
|
40
|
+
|
|
41
|
+
raise ArgumentError, "#{dashboard_class.name} #{action_name}: uploads: names #{unknown.join(', ')}, " \
|
|
42
|
+
'which are not attachment attributes'
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def param_schemas(definition)
|
|
46
|
+
definition.uploads.keys.to_h do |attribute|
|
|
47
|
+
[param_name(attribute),
|
|
48
|
+
{ type: 'string', description: "An upload_id from uploads_prepare, to set #{attribute} to that file." }]
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def resolve_params(definition, admin, params)
|
|
53
|
+
tool = Actions.tool_name(definition)
|
|
54
|
+
definition.uploads.each_key.with_object(params.dup) do |attribute, resolved|
|
|
55
|
+
upload_id = resolved.delete(param_name(attribute))
|
|
56
|
+
next if upload_id.blank?
|
|
57
|
+
|
|
58
|
+
resolved[attribute] = Uploads.resolve(admin:, upload_id:, tool:, attribute: attribute.to_s,
|
|
59
|
+
rules: Uploads.rules_for(definition, attribute))
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
private
|
|
64
|
+
|
|
65
|
+
def validate_rules!(context, rules)
|
|
66
|
+
raise ArgumentError, "#{context} must be a hash of rules" unless rules.is_a?(Hash)
|
|
67
|
+
|
|
68
|
+
rules = rules.symbolize_keys
|
|
69
|
+
unknown = rules.keys - RULE_KEYS
|
|
70
|
+
raise ArgumentError, "#{context}: unknown rule(s) #{unknown.join(', ')}" if unknown.any?
|
|
71
|
+
unless rules[:content_types].nil? || content_types?(rules[:content_types])
|
|
72
|
+
raise ArgumentError, "#{context}: content_types: must be a hash of extension to content type, " \
|
|
73
|
+
"such as { '.png' => 'image/png' }"
|
|
74
|
+
end
|
|
75
|
+
return rules if rules[:max_size].nil? || positive_integer?(rules[:max_size])
|
|
76
|
+
|
|
77
|
+
raise ArgumentError, "#{context}: max_size: must be a positive number of bytes"
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def positive_integer?(value)
|
|
81
|
+
value.is_a?(Integer) && value.positive?
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def content_types?(content_types)
|
|
85
|
+
content_types.is_a?(Hash) && content_types.any? &&
|
|
86
|
+
content_types.all? { |extension, type| extension.to_s.match?(/\A\.\w+\z/) && type.is_a?(String) }
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def param_name(attribute)
|
|
90
|
+
:"#{attribute}_upload_id"
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def attachment_attributes(dashboard_class)
|
|
94
|
+
dashboard_class.new.attribute_types.filter_map do |attribute, field_spec|
|
|
95
|
+
attribute if FieldSerializer.serializer_for(field_spec) == :attachment
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def config
|
|
100
|
+
Administrate::MCP.config.uploads
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
end
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Administrate
|
|
4
|
+
module MCP
|
|
5
|
+
module Uploads
|
|
6
|
+
# The default upload storage, on a Shrine storage (`:cache` by default). It presigns a POST
|
|
7
|
+
# whose policy bounds the content length, so the storage itself refuses a file above the
|
|
8
|
+
# maximum size. Fetching copies the uploaded object to a key no URL points to, so what is
|
|
9
|
+
# checked and attached cannot be replaced afterwards; on S3 the copy happens server side.
|
|
10
|
+
# Metadata comes from the uploader's own extraction, so the host's `determine_mime_type` and
|
|
11
|
+
# `store_dimensions` plugins apply, and runs only once the size is known to be acceptable.
|
|
12
|
+
class ShrineStorage
|
|
13
|
+
Upload = Data.define(:mime_type, :size, :value)
|
|
14
|
+
|
|
15
|
+
def initialize(uploader: 'Shrine', storage_key: :cache)
|
|
16
|
+
@uploader = uploader
|
|
17
|
+
@storage_key = storage_key.to_sym
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def presignable?
|
|
21
|
+
storage.respond_to?(:presign)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def description
|
|
25
|
+
"Shrine storage :#{@storage_key} (#{storage.class.name})"
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def presign(key, content_type:, max_size:, expires_in:)
|
|
29
|
+
presigned = storage.presign(key, method: :post, content_type:, content_length_range: 1..max_size,
|
|
30
|
+
signature_expiration: expires_in.seconds.from_now)
|
|
31
|
+
{ method: 'POST', url: presigned[:url], fields: presigned[:fields] }
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def fetch(key, filename:, max_size:)
|
|
35
|
+
original = uploaded_file(key, filename)
|
|
36
|
+
return unless original.exists?
|
|
37
|
+
|
|
38
|
+
copy = uploader.upload(original, location: "#{SecureRandom.uuid}#{File.extname(key)}")
|
|
39
|
+
copy.open do
|
|
40
|
+
next Upload.new(mime_type: nil, size: copy.size, value: copy.data) if copy.size.to_i > max_size
|
|
41
|
+
|
|
42
|
+
describe(copy, filename)
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def delete(value)
|
|
47
|
+
uploader_class.uploaded_file(value).delete
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
private
|
|
51
|
+
|
|
52
|
+
def describe(file, filename)
|
|
53
|
+
metadata = file.metadata.merge(uploader.extract_metadata(file).compact, 'filename' => filename)
|
|
54
|
+
Upload.new(mime_type: metadata['mime_type'], size: metadata['size'],
|
|
55
|
+
value: file.data.merge('metadata' => metadata))
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def uploaded_file(key, filename)
|
|
59
|
+
uploader_class.uploaded_file('storage' => @storage_key.to_s, 'id' => key,
|
|
60
|
+
'metadata' => { 'filename' => filename })
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def uploader
|
|
64
|
+
uploader_class.new(@storage_key)
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def uploader_class
|
|
68
|
+
@uploader.is_a?(Class) ? @uploader : @uploader.to_s.constantize
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def storage
|
|
72
|
+
uploader_class.storages.fetch(@storage_key)
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Administrate
|
|
4
|
+
module MCP
|
|
5
|
+
# Presigned uploads. `prepare` checks that the caller may use the target action, records a
|
|
6
|
+
# batch, and hands out one presigned upload per file. `resolve` turns an upload_id back into an
|
|
7
|
+
# attachment value for that same action and attribute: it copies the uploaded object to a key
|
|
8
|
+
# the client cannot write to, checks the copy's real size and content type, and remembers the
|
|
9
|
+
# copy so a retried action gets the same file.
|
|
10
|
+
module Uploads
|
|
11
|
+
class << self
|
|
12
|
+
def prepare(admin:, scopes:, tool:, attribute:, files:)
|
|
13
|
+
definition = upload_action!(admin, scopes, tool.to_s, attribute.to_sym)
|
|
14
|
+
rules = rules_for(definition, attribute.to_sym)
|
|
15
|
+
storage = presignable_storage!
|
|
16
|
+
entries = build_entries(files, rules, tool: tool.to_s, attribute: attribute.to_s)
|
|
17
|
+
UploadBatch.create!(admin:, expires_at: config.batch_ttl.seconds.from_now, files: entries)
|
|
18
|
+
|
|
19
|
+
entries.to_h do |entry|
|
|
20
|
+
presigned = storage.presign(entry[:key], content_type: entry[:content_type], max_size: rules.max_size,
|
|
21
|
+
expires_in: config.url_ttl.to_i)
|
|
22
|
+
[entry[:filename], { upload_id: entry[:upload_id], **presigned }]
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def resolve(admin:, upload_id:, tool:, attribute:, rules:)
|
|
27
|
+
batch, entry = find_entry!(admin, upload_id.to_s, tool, attribute)
|
|
28
|
+
return entry['value'] if entry['value']
|
|
29
|
+
|
|
30
|
+
record_value(batch, upload_id.to_s, fetch!(upload_id, entry, rules).value)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def rules_for(definition, attribute)
|
|
34
|
+
config.rules(**definition.uploads.fetch(attribute))
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
private
|
|
38
|
+
|
|
39
|
+
def config
|
|
40
|
+
Administrate::MCP.config.uploads
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def upload_action!(admin, scopes, tool, attribute)
|
|
44
|
+
definition = Actions.definitions.find { |candidate| Actions.tool_name(candidate) == tool }
|
|
45
|
+
return definition if definition&.uploads&.key?(attribute) && Actions.available_to?(admin, definition, scopes:)
|
|
46
|
+
|
|
47
|
+
raise InvalidArgumentError, "No action #{tool} that accepts an upload for #{attribute} is available to you"
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def presignable_storage!
|
|
51
|
+
storage = config.storage
|
|
52
|
+
raise ConfigurationError, 'No upload storage is configured; set config.uploads.storage' unless storage
|
|
53
|
+
return storage if storage.presignable?
|
|
54
|
+
|
|
55
|
+
raise ConfigurationError, "#{storage.description} cannot presign uploads. Configure a storage that " \
|
|
56
|
+
'can, such as Shrine::Storage::S3, or set config.uploads.storage'
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def build_entries(files, rules, **target)
|
|
60
|
+
raise InvalidArgumentError, 'files must name at least one file' if files.blank?
|
|
61
|
+
if files.size > config.max_files
|
|
62
|
+
raise InvalidArgumentError, "files can name at most #{config.max_files} files"
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
errors = files.flat_map { |filename, size| entry_errors(filename.to_s, size, rules) }
|
|
66
|
+
raise InvalidArgumentError, errors.join('; ') if errors.any?
|
|
67
|
+
|
|
68
|
+
files.map { |filename, size| build_entry(filename.to_s, Integer(size), rules, **target) }
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def entry_errors(filename, size, rules)
|
|
72
|
+
errors = []
|
|
73
|
+
unless rules.content_type_for(filename)
|
|
74
|
+
errors << "#{filename} is not an allowed file type (#{rules.content_types.keys.join(', ')})"
|
|
75
|
+
end
|
|
76
|
+
unless Integer(size, exception: false)&.between?(1, rules.max_size)
|
|
77
|
+
errors << "#{filename} size must be between 1 and #{rules.max_size} bytes"
|
|
78
|
+
end
|
|
79
|
+
errors
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def build_entry(filename, size, rules, tool:, attribute:)
|
|
83
|
+
upload_id = SecureRandom.uuid
|
|
84
|
+
extension = File.extname(filename).downcase
|
|
85
|
+
{ upload_id:, key: "#{upload_id}#{extension}", filename:, content_type: rules.content_type_for(filename),
|
|
86
|
+
size:, tool:, attribute: }
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def find_entry!(admin, upload_id, tool, attribute)
|
|
90
|
+
batch = UploadBatch.with_upload(upload_id).find_by(admin:)
|
|
91
|
+
raise InvalidArgumentError, "Upload #{upload_id} not found" unless batch
|
|
92
|
+
raise InvalidArgumentError, "Upload #{upload_id} expired at #{batch.expires_at.iso8601}" if batch.expired?
|
|
93
|
+
|
|
94
|
+
entry = batch.file(upload_id)
|
|
95
|
+
unless entry['tool'] == tool && entry['attribute'] == attribute
|
|
96
|
+
raise InvalidArgumentError, "Upload #{upload_id} was prepared for #{entry['tool']} #{entry['attribute']}"
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
[batch, entry]
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def fetch!(upload_id, entry, rules)
|
|
103
|
+
upload = config.storage.fetch(entry['key'], filename: entry['filename'], max_size: rules.max_size)
|
|
104
|
+
raise InvalidArgumentError, "Upload #{upload_id} has not been uploaded yet" unless upload
|
|
105
|
+
|
|
106
|
+
error = content_error(upload_id, upload, rules)
|
|
107
|
+
return upload unless error
|
|
108
|
+
|
|
109
|
+
config.storage.delete(upload.value)
|
|
110
|
+
raise InvalidArgumentError, error
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def record_value(batch, upload_id, value)
|
|
114
|
+
UploadBatch.transaction do
|
|
115
|
+
locked = UploadBatch.lock.find(batch.id)
|
|
116
|
+
recorded = locked.file(upload_id)['value']
|
|
117
|
+
next locked.record_value!(upload_id, value) && value unless recorded
|
|
118
|
+
|
|
119
|
+
config.storage.delete(value)
|
|
120
|
+
recorded
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
def content_error(upload_id, upload, rules)
|
|
125
|
+
if upload.size.to_i > rules.max_size
|
|
126
|
+
"Upload #{upload_id} is #{upload.size} bytes, the maximum is #{rules.max_size}"
|
|
127
|
+
elsif !rules.allowed_content_type?(upload.mime_type)
|
|
128
|
+
"Upload #{upload_id} is #{upload.mime_type || 'of an unknown type'}, " \
|
|
129
|
+
"expected one of #{rules.content_types.values.uniq.join(', ')}"
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
end
|
|
135
|
+
end
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Administrate
|
|
4
|
+
module MCP
|
|
5
|
+
# The files an admin was handed presigned upload URLs for. Each entry of `files` holds the
|
|
6
|
+
# upload_id given to the client, the storage key, the declared filename, content type and size,
|
|
7
|
+
# the action tool and attribute it was prepared for, and, once resolved, the checked value.
|
|
8
|
+
class UploadBatch < ApplicationRecord
|
|
9
|
+
self.table_name = 'administrate_mcp_upload_batches'
|
|
10
|
+
|
|
11
|
+
belongs_to_admin
|
|
12
|
+
|
|
13
|
+
scope :with_upload, ->(upload_id) { where('files @> ?', [{ upload_id: }].to_json) }
|
|
14
|
+
scope :expired, ->(at = Time.current) { where(expires_at: ...at) }
|
|
15
|
+
|
|
16
|
+
def expired?
|
|
17
|
+
expires_at <= Time.current
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def file(upload_id)
|
|
21
|
+
files.find { |entry| entry['upload_id'] == upload_id }
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def record_value!(upload_id, value)
|
|
25
|
+
update!(files: files.map { |entry| entry['upload_id'] == upload_id ? entry.merge('value' => value) : entry })
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class CreateAdministrateModelContextProtocolUploadBatches < ActiveRecord::Migration[8.1]
|
|
4
|
+
def change
|
|
5
|
+
admin_foreign_key = Administrate::MCP.config.admin_foreign_key
|
|
6
|
+
|
|
7
|
+
create_table :administrate_mcp_upload_batches, id: :uuid, if_not_exists: true do |t|
|
|
8
|
+
t.uuid admin_foreign_key, null: false
|
|
9
|
+
t.datetime :expires_at, null: false
|
|
10
|
+
t.jsonb :files, null: false, default: []
|
|
11
|
+
|
|
12
|
+
t.timestamps
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
add_index :administrate_mcp_upload_batches, admin_foreign_key, if_not_exists: true
|
|
16
|
+
add_index :administrate_mcp_upload_batches, :files, using: :gin, opclass: :jsonb_path_ops, if_not_exists: true
|
|
17
|
+
end
|
|
18
|
+
end
|
data/docs/configuration.md
CHANGED
|
@@ -111,6 +111,7 @@ class Configuration
|
|
|
111
111
|
:persist_feedback,
|
|
112
112
|
:feedback_tool,
|
|
113
113
|
:sidekiq_stats_provider,
|
|
114
|
+
:action_data_max_bytes,
|
|
114
115
|
:admin_route_namespace,
|
|
115
116
|
:admin_url_options,
|
|
116
117
|
:skipped_field_classes,
|
|
@@ -148,6 +149,7 @@ class Configuration
|
|
|
148
149
|
@persist_feedback = false
|
|
149
150
|
@feedback_tool = true
|
|
150
151
|
@sidekiq_stats_provider = nil
|
|
152
|
+
@action_data_max_bytes = 32_768
|
|
151
153
|
end
|
|
152
154
|
|
|
153
155
|
def assign_fields
|
|
@@ -197,11 +199,13 @@ end
|
|
|
197
199
|
| `persist_feedback` | `false` | Whether `report_mcp_improvement` creates an `Administrate::MCP::Feedback` row before calling `on_feedback`. False needs no `administrate_mcp_feedbacks` table at all |
|
|
198
200
|
| `feedback_tool` | `true` | Whether `report_mcp_improvement` is published |
|
|
199
201
|
| `sidekiq_stats_provider` | `nil` | Object answering `counts`, `total_counts`, `queues`, `stats_cleared_at`; a class name String or a Proc is resolved lazily so autoloaded providers can be named in an initializer |
|
|
202
|
+
| `action_data_max_bytes` | `32_768` | Largest `data` an `mcp_action` may return, in bytes of JSON; larger data is an error. `nil` removes the limit. See [Returning data from an action](dashboards.md#returning-data-from-an-action) |
|
|
200
203
|
| `admin_route_namespace` | `:admin` | Namespace record URLs are built from |
|
|
201
204
|
| `admin_url_options` | `{}` | Options passed to `polymorphic_url`; when no `:host` is given, host, protocol and port are taken from `admin_origin` |
|
|
202
205
|
| `skipped_field_classes` | Password | Field class names never serialized |
|
|
203
206
|
| `has_many_field_classes` | HasMany | Field class names treated as expandable collections |
|
|
204
207
|
| `field_serializers` | see above | Field class name to serializer |
|
|
208
|
+
| `uploads` | disabled | Presigned uploads: `enabled`, `storage`, `allowed_content_types`, `max_size`, `max_files`, `url_ttl`, `batch_ttl`. See [Presigned uploads](uploads.md) |
|
|
205
209
|
|
|
206
210
|
## Authorization adapters
|
|
207
211
|
|
data/docs/dashboards.md
CHANGED
|
@@ -17,6 +17,14 @@ class OrderDashboard < Administrate::BaseDashboard
|
|
|
17
17
|
params: { reason: { type: 'string', description: 'Why the order is being refunded.' } } do |record:, admin:, params:|
|
|
18
18
|
Orders::Refund.call!(order: record, admin:, reason: params[:reason])
|
|
19
19
|
end
|
|
20
|
+
|
|
21
|
+
mcp_action :import,
|
|
22
|
+
on: :collection,
|
|
23
|
+
destructive: false,
|
|
24
|
+
description: 'Import an order from a marketplace.',
|
|
25
|
+
params: { reference: 'The marketplace order reference.' } do |admin:, params:|
|
|
26
|
+
Orders::Import.call!(reference: params[:reference], admin:).order
|
|
27
|
+
end
|
|
20
28
|
end
|
|
21
29
|
```
|
|
22
30
|
|
|
@@ -33,10 +41,91 @@ base class, is not applied to every resource. A subclass that wants one declares
|
|
|
33
41
|
`scoped_resource`.
|
|
34
42
|
- `COLLECTION_FILTERS` are published as filters; a one-argument lambda is a boolean filter, a
|
|
35
43
|
two-argument one takes a value. Foreign key columns are filterable without being declared.
|
|
36
|
-
- `mcp_action` publishes one tool per declaration
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
44
|
+
- `mcp_action` publishes one tool per declaration, named `<resource>_<action>` (`order_refund`). It
|
|
45
|
+
requires the OAuth `write` scope, and the authorization predicate (`refund?` for `:refund` by
|
|
46
|
+
default, or `predicate:`, also spelled `pundit:`), checked through `config.authorization`. Every
|
|
47
|
+
call is reported to `config.on_tool_call`.
|
|
48
|
+
- The input schema lists `params` and closes the object (`additionalProperties: false`), so an
|
|
49
|
+
argument that is not declared is refused before the action runs, and the block only ever sees
|
|
50
|
+
declared params.
|
|
51
|
+
- The block's result decides the answer. A result answering `success? == false` is an error, with
|
|
52
|
+
the result's `error` as the message when it has one. An Active Record object that was never
|
|
53
|
+
saved or has errors is an error too, with its validation messages. So is `false`, the result of
|
|
54
|
+
a failed `update` or of a `destroy` a callback aborted; for a member action the message is the
|
|
55
|
+
loaded record's validation messages when it has any. Anything else is a success, including a
|
|
56
|
+
record the block destroyed. To send data back with the answer, return an
|
|
57
|
+
`Administrate::MCP::ActionResult`; see [Returning data from an action](#returning-data-from-an-action).
|
|
58
|
+
- The tool is announced as destructive unless the declaration says `destructive: false`. Clients
|
|
59
|
+
may ask for confirmation before running a destructive tool, so set it on actions that only add
|
|
60
|
+
or prepare something.
|
|
61
|
+
- A member action (`on: :member`, the default) takes an `id` (or slug), loads the record and checks
|
|
62
|
+
the predicate against it. The block receives `record:`, `admin:` and `params:`. The response
|
|
63
|
+
echoes the `id` the caller passed.
|
|
64
|
+
- A collection action (`on: :collection`) takes no `id` and loads nothing, so it suits creating a
|
|
65
|
+
record or preparing something that is not a record yet. The predicate is checked against a new
|
|
66
|
+
instance of the model, as Administrate does for `new` and `create`, both when the tool list is
|
|
67
|
+
built and on every call; a creating action usually declares `predicate: :create?`. The block
|
|
68
|
+
receives `admin:` and `params:`, and owns any scoping of what it creates, such as a tenant,
|
|
69
|
+
since no record lookup does it. The response carries the primary key of the record the block
|
|
70
|
+
returns, so return the created record for the client to act on it; a block that returns
|
|
71
|
+
something else gets a response without `id`.
|
|
72
|
+
- `uploads:` (`true`, a list of attachment attributes, or per-attribute `content_types:` and
|
|
73
|
+
`max_size:`) adds an optional `<attribute>_upload_id` param for each of them, and the block
|
|
74
|
+
receives the uploaded file as `params[:<attribute>]`. See [Presigned uploads](uploads.md).
|
|
75
|
+
|
|
76
|
+
## Returning data from an action
|
|
77
|
+
|
|
78
|
+
An action answers `{ status, model, id, action }` by default, as JSON text and, identically, as the
|
|
79
|
+
result's `structuredContent`. When the client needs more than that, such as what an import created
|
|
80
|
+
and what it skipped, the block returns an `Administrate::MCP::ActionResult` and the answer gains a
|
|
81
|
+
`data` key:
|
|
82
|
+
|
|
83
|
+
```ruby
|
|
84
|
+
mcp_action :import_batch,
|
|
85
|
+
on: :collection,
|
|
86
|
+
description: 'Import orders from a marketplace export.',
|
|
87
|
+
params: { references: { type: 'array', items: { type: 'string' } } } do |admin:, params:|
|
|
88
|
+
report = Orders::ImportBatch.call!(references: params[:references], admin:)
|
|
89
|
+
next Administrate::MCP::ActionResult.failure('No order matched', data: { unknown: report.unknown }) if report.empty?
|
|
90
|
+
|
|
91
|
+
Administrate::MCP::ActionResult.success(record: report.batch,
|
|
92
|
+
data: { created: report.created.size, unknown: report.unknown })
|
|
93
|
+
end
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{ "status": "ok", "model": "order", "id": 42, "action": "import_batch", "data": { "created": 3, "unknown": ["X-9"] } }
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
- `ActionResult.success(record:, data:)`: `record` is optional and is checked as if the block had
|
|
101
|
+
returned it, so an unsaved or invalid record is still an error, and a collection action still
|
|
102
|
+
answers its `id`.
|
|
103
|
+
- `ActionResult.failure(message, data:)` is an error with `message`, or `<action> failed` without
|
|
104
|
+
one. The error's first content block stays the message alone. When there is data, a second block
|
|
105
|
+
carries `{ "error": message, "data": … }` as JSON, and the result's `structuredContent` carries the
|
|
106
|
+
same object, so clients that only read the content still see the data.
|
|
107
|
+
- These two are the only constructors. Any result object that answers `mcp_data` with a Hash works
|
|
108
|
+
the same way, so a host's own service result can carry its data without being wrapped; `success?`
|
|
109
|
+
and `error` are read from it as for any other result.
|
|
110
|
+
- A plain Hash returned by the block is not sent back, as before: data reaches the client only when
|
|
111
|
+
the block asks for it, never because a service happened to return a Hash.
|
|
112
|
+
- `data` must be a Hash of JSON values: Hashes with String or Symbol keys, Arrays, Strings, Symbols,
|
|
113
|
+
Integers, finite Floats, `true`, `false` and `nil`, nested at most 32 levels deep. Strings and
|
|
114
|
+
keys must be valid UTF-8 or convertible to it, so check bytes read from a file. Convert
|
|
115
|
+
anything else, such as a time (`at.iso8601`) or a record (`record.id`), yourself. The engine
|
|
116
|
+
encodes a plain copy it builds from those values, so an object's own `as_json` never runs, and a
|
|
117
|
+
key given both as a String and as a Symbol is refused rather than sent twice. The copy's JSON may
|
|
118
|
+
be at most `config.action_data_max_bytes` (32 KB by default; `nil` removes the limit), so that an
|
|
119
|
+
action cannot fill the client's context. Return counts and the few items the client must act on,
|
|
120
|
+
not every row.
|
|
121
|
+
- Data that breaks a rule is answered as an error naming the offending path, for example
|
|
122
|
+
`data.report.rows[1] (Object) is not a JSON value`. The block has already run by then, so the
|
|
123
|
+
message says the action ran: fix the action rather than retrying the call.
|
|
124
|
+
- `data` reaches the client as it is, without the protections fields get from
|
|
125
|
+
`skipped_field_classes` and the field serializers. Don't return secrets, tokens or credentials. A
|
|
126
|
+
download URL is a bearer credential that ends up in transcripts and client logs, so make it
|
|
127
|
+
short-lived. Strings that came from end users (names, notes, references) are untrusted text in the
|
|
128
|
+
model's context, as they are in any field.
|
|
40
129
|
|
|
41
130
|
## Search
|
|
42
131
|
|
data/docs/development.md
CHANGED
|
@@ -13,7 +13,10 @@ spec helper catches `ActiveRecord::NoDatabaseError` and calls `ActiveRecord::Tas
|
|
|
13
13
|
so no separate `createdb` step is needed. Point the specs at another Postgres with
|
|
14
14
|
`ADMINISTRATE_MCP_DB_HOST`, `_PORT`, `_USER`, `_PASSWORD` and `_NAME`.
|
|
15
15
|
|
|
16
|
-
The dummy application under `spec/dummy` has an `Admin`, a `Widget` (with `MCP_BASE_SCOPE
|
|
17
|
-
collection filters
|
|
16
|
+
The dummy application under `spec/dummy` has an `Admin`, a `Widget` (with `MCP_BASE_SCOPE`,
|
|
17
|
+
collection filters, a Shrine `picture` attachment shown through a host-style `PictureField`, and a
|
|
18
|
+
collection `mcp_action` that accepts uploads) and a `Gadget` (with a `belongs_to` and a member
|
|
19
|
+
`mcp_action`). Upload specs use the `with presignable storage` shared context, which swaps the Shrine
|
|
20
|
+
cache storage for an S3 storage with a stubbed client.
|
|
18
21
|
|
|
19
22
|
See [CONTRIBUTING.md](../CONTRIBUTING.md) for how to propose a change.
|