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
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 7e0b5788d3dd59f527d55db5f4e6e4d748c23f1c6d4f247c2afaa660e4dce89e
|
|
4
|
+
data.tar.gz: 932950d82e3472408f440cdb2a736b8107978ca8016c55e625e1221e21e99ddc
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 41f1ca74dbe3ed51314f8ec39ea8f38d99ba1831dd725e4e19ca17e8ef940b31d359f7651526a8fe1b8dfb53bcfb74ed2cba615d45e48a8cba230cb3b463711d
|
|
7
|
+
data.tar.gz: e1575180b4778ba2e68addc80c8c90441045436588281fc413d66a6abe43554be3eccc39d6a3965f7a927949f4ae911019890bb0e931bb31cb5a7ee0c6c2f767
|
data/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,71 @@ minor release may change behaviour a host depends on; the entry says so when it
|
|
|
8
8
|
|
|
9
9
|
## [Unreleased]
|
|
10
10
|
|
|
11
|
+
## [0.5.0] - 2026-10-22
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- An `mcp_action` block can send data back to the client. It returns
|
|
16
|
+
`Administrate::MCP::ActionResult.success(record:, data:)`, or any result object answering
|
|
17
|
+
`mcp_data`, and the answer gains a `data` key next to `status`, `model`, `id` and `action`, which
|
|
18
|
+
are unchanged. The record, optional, goes through the same checks as a record returned directly,
|
|
19
|
+
so an unsaved or invalid one is still an error and a collection action still answers its `id`.
|
|
20
|
+
`ActionResult.failure(message, data:)` is an error whose first content block is the message, as
|
|
21
|
+
before; when there is data, a second block carries `{ "error": message, "data": … }` as JSON and
|
|
22
|
+
the result's `structuredContent` carries the same object. The data must be a Hash of plain JSON
|
|
23
|
+
values nested at most 32 levels deep, with valid UTF-8 strings; the engine encodes a copy
|
|
24
|
+
built from those values, never the host's objects, and its JSON may be at most
|
|
25
|
+
`config.action_data_max_bytes` (new, 32 KB by default, `nil` for no limit). Anything else is
|
|
26
|
+
answered as an error naming the offending path and saying the action ran. A plain Hash returned
|
|
27
|
+
by a block is still not sent back. See
|
|
28
|
+
[Returning data from an action](docs/dashboards.md#returning-data-from-an-action).
|
|
29
|
+
|
|
30
|
+
### Changed
|
|
31
|
+
|
|
32
|
+
- A successful `mcp_action` call now also returns its answer as the result's `structuredContent`,
|
|
33
|
+
the same object as the JSON in its text content, which is unchanged.
|
|
34
|
+
- A tool error may now carry a second content block. Clients that read only the first block still
|
|
35
|
+
get the message on its own; only failures that return data add the second block.
|
|
36
|
+
|
|
37
|
+
## [0.4.0] - 2026-10-21
|
|
38
|
+
|
|
39
|
+
### Added
|
|
40
|
+
|
|
41
|
+
- Collection-level write actions: `mcp_action name, on: :collection, ...` publishes a tool with no
|
|
42
|
+
`id` in its input schema. Nothing is loaded; the block receives `admin:` and `params:`, and the
|
|
43
|
+
authorization predicate, `<name>?` by default as for member actions and overridable with
|
|
44
|
+
`predicate:` or `pundit:`, is checked against a new instance of the model through
|
|
45
|
+
`config.authorization`, when the tool list is built and on every call. The `write` scope gate,
|
|
46
|
+
the `on_tool_call` audit and the error reporting work as for member actions, and the tool keeps
|
|
47
|
+
the `<resource>_<action>` name. When the block returns an Active Record object, the response
|
|
48
|
+
includes its primary key as `id`. `on: :member` stays the default.
|
|
49
|
+
- Presigned uploads for Shrine attachments, off until `config.uploads.enabled` is set. The
|
|
50
|
+
`uploads_prepare` tool takes the target action's `tool` name, an `attribute` and `files`, an
|
|
51
|
+
object of filename to size in bytes. It is only published to, and only answers, a caller
|
|
52
|
+
authorized for an action that accepts uploads for that attribute. It records an
|
|
53
|
+
`administrate_mcp_upload_batches` row and returns `{ filename => { upload_id, method, url,
|
|
54
|
+
fields } }`, one presigned `POST` per file whose policy bounds the content length. An
|
|
55
|
+
`mcp_action` declared with `uploads:` (`true`, a list of attributes, or per-attribute
|
|
56
|
+
`content_types:` and `max_size:`) takes an optional `<attribute>_upload_id` for each attachment
|
|
57
|
+
attribute; the engine resolves it and the block receives the file as `params[:<attribute>]`.
|
|
58
|
+
Resolving checks the owning admin (another admin's id is not found), the action and attribute
|
|
59
|
+
the upload was prepared for, the batch expiry, that the file was uploaded, and its real size
|
|
60
|
+
and content type, on a copy under a key no URL points to; the copy is reused if the same id is
|
|
61
|
+
passed again. Defaults: png, jpeg and webp, 10 MB, 10 files per call, 15-minute URLs, 1-hour
|
|
62
|
+
batches. `Administrate::MCP::CleanExpiredUploadBatches` deletes expired batches. The default
|
|
63
|
+
storage is the Shrine `:cache` storage, replaceable through `config.uploads.storage`; the gem
|
|
64
|
+
gains no dependency. Hosts that enable uploads need the new migration
|
|
65
|
+
(`bin/rails administrate_mcp:install:migrations`).
|
|
66
|
+
|
|
67
|
+
### Changed
|
|
68
|
+
|
|
69
|
+
- **Behaviour change for hosts:** an `mcp_action` block that returns an Active Record object that
|
|
70
|
+
was never saved or has errors is now reported as an error, with the record's validation messages,
|
|
71
|
+
instead of `status: ok`. A record the block destroyed is still a success. A block that returns
|
|
72
|
+
`false`, as `record.update(...)` does on a validation error and `record.destroy` does when a
|
|
73
|
+
callback aborts it, is now an error too, with the loaded record's validation messages for a member
|
|
74
|
+
action when it has any. A block that returned `false` to mean success must return something else.
|
|
75
|
+
|
|
11
76
|
## [0.3.1] - 2026-10-20
|
|
12
77
|
|
|
13
78
|
### Security
|
|
@@ -138,7 +203,9 @@ minor release may change behaviour a host depends on; the entry says so when it
|
|
|
138
203
|
took the gem from git before 0.1.0 must reinstall its migrations rather than migrate
|
|
139
204
|
incrementally.
|
|
140
205
|
|
|
141
|
-
[Unreleased]: https://github.com/sorare/administrate-mcp/compare/v0.
|
|
206
|
+
[Unreleased]: https://github.com/sorare/administrate-mcp/compare/v0.5.0...HEAD
|
|
207
|
+
[0.5.0]: https://github.com/sorare/administrate-mcp/compare/v0.4.0...v0.5.0
|
|
208
|
+
[0.4.0]: https://github.com/sorare/administrate-mcp/compare/v0.3.1...v0.4.0
|
|
142
209
|
[0.3.1]: https://github.com/sorare/administrate-mcp/compare/v0.3.0...v0.3.1
|
|
143
210
|
[0.3.0]: https://github.com/sorare/administrate-mcp/compare/v0.2.0...v0.3.0
|
|
144
211
|
[0.2.0]: https://github.com/sorare/administrate-mcp/compare/v0.1.0...v0.2.0
|
data/README.md
CHANGED
|
@@ -21,6 +21,7 @@ permissions the admin UI enforces.
|
|
|
21
21
|
- [Configuration](#configuration)
|
|
22
22
|
- [Routes](#routes)
|
|
23
23
|
- [Dashboard declarations](#dashboard-declarations)
|
|
24
|
+
- [Presigned uploads](#presigned-uploads)
|
|
24
25
|
- [Authentication](#authentication)
|
|
25
26
|
- [OAuth](#oauth)
|
|
26
27
|
- [Improving the server from its own use](#improving-the-server-from-its-own-use)
|
|
@@ -45,7 +46,14 @@ about your application; everything host-specific goes through `Administrate::MCP
|
|
|
45
46
|
- Three generic tools built from every Administrate dashboard: `admin_resource_list_resources`,
|
|
46
47
|
`admin_resource_list`, `admin_resource_show`.
|
|
47
48
|
- Write actions declared per dashboard with `mcp_action`, each published as its own tool, gated by
|
|
48
|
-
the `write` scope (an API key with write access, or an OAuth token granted it) and the resource's
|
|
49
|
+
the `write` scope (an API key with write access, or an OAuth token granted it) and the resource's
|
|
50
|
+
own authorization predicate: on the loaded record for a member action, or on the model class for a
|
|
51
|
+
collection action (`on: :collection`), such as a create, that takes no `id`.
|
|
52
|
+
- Presigned uploads for Shrine attachments, opt-in: `uploads_prepare` hands out presigned `POST`
|
|
53
|
+
URLs for one action and attribute, and an action declared with `uploads:` takes an
|
|
54
|
+
`<attribute>_upload_id` for each attachment attribute. The file's owner, target, expiry, real size
|
|
55
|
+
and real content type are checked on a copy the client cannot overwrite before the action runs.
|
|
56
|
+
See [Presigned uploads](docs/uploads.md).
|
|
49
57
|
- Three ways to authenticate a caller: API keys stored as a digest, an external identity provider
|
|
50
58
|
through `identity_fallback` (a Cloudflare Access verifier ships with the gem), and an optional
|
|
51
59
|
built-in OAuth 2.1 server with Dynamic Client Registration, PKCE and refresh tokens, on by default
|
|
@@ -157,8 +165,8 @@ bin/rails db:migrate
|
|
|
157
165
|
```
|
|
158
166
|
|
|
159
167
|
The tables are `administrate_mcp_api_keys`, `administrate_mcp_feedbacks`,
|
|
160
|
-
`administrate_mcp_oauth_applications`, `administrate_mcp_oauth_access_grants
|
|
161
|
-
`administrate_mcp_oauth_access_tokens`. They use uuid primary keys and a uuid column, `admin_id` by
|
|
168
|
+
`administrate_mcp_oauth_applications`, `administrate_mcp_oauth_access_grants`,
|
|
169
|
+
`administrate_mcp_oauth_access_tokens` and `administrate_mcp_upload_batches`. They use uuid primary keys and a uuid column, `admin_id` by
|
|
162
170
|
default, that is indexed but carries no foreign key constraint, so the engine works with any admin
|
|
163
171
|
table. Set `config.admin_foreign_key` before running the migrations if the host's own admin table
|
|
164
172
|
already uses a different column name and renaming it is not an option, for example a live
|
|
@@ -166,6 +174,7 @@ credentials table.
|
|
|
166
174
|
|
|
167
175
|
`administrate_mcp_feedbacks` is only needed when `config.persist_feedback` is `true`; leave it
|
|
168
176
|
`false`, the default, and the migration ships but the table is never read from or written to.
|
|
177
|
+
Likewise, `administrate_mcp_upload_batches` is only used once `config.uploads.enabled` is `true`.
|
|
169
178
|
|
|
170
179
|
## Quick start
|
|
171
180
|
|
|
@@ -219,6 +228,11 @@ helper adds: [docs/routes.md](docs/routes.md).
|
|
|
219
228
|
and `mcp_action`, the constants and macro that turn one dashboard into an MCP resource with its own
|
|
220
229
|
readable fields and writable actions: [docs/dashboards.md](docs/dashboards.md).
|
|
221
230
|
|
|
231
|
+
## Presigned uploads
|
|
232
|
+
|
|
233
|
+
How a client uploads a file to a presigned URL and sets it on an attachment through an action, the
|
|
234
|
+
checks on the uploaded file, and the storage it goes to: [docs/uploads.md](docs/uploads.md).
|
|
235
|
+
|
|
222
236
|
## Authentication
|
|
223
237
|
|
|
224
238
|
How a request is authenticated (API key, then OAuth token, then `identity_fallback`), how to issue
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Administrate
|
|
4
|
+
module MCP
|
|
5
|
+
# What an `mcp_action` block may return to send data back to the client. `record` goes through
|
|
6
|
+
# the same checks as a record returned directly, and gives a collection action its `id`; `data`
|
|
7
|
+
# is answered as `mcp_data`, which the engine adds to the response under `data`, or to the error
|
|
8
|
+
# of a failure. Any result object that answers `mcp_data` works the same way.
|
|
9
|
+
class ActionResult
|
|
10
|
+
attr_reader :record, :data, :error
|
|
11
|
+
|
|
12
|
+
alias mcp_data data
|
|
13
|
+
|
|
14
|
+
private_class_method :new
|
|
15
|
+
|
|
16
|
+
def self.success(record: nil, data: nil)
|
|
17
|
+
new(record:, data:, error: nil, success: true)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def self.failure(error = nil, data: nil)
|
|
21
|
+
new(record: nil, data:, error:, success: false)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def initialize(record:, data:, error:, success:)
|
|
25
|
+
@record = record
|
|
26
|
+
@data = data
|
|
27
|
+
@error = error
|
|
28
|
+
@success = success
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def success?
|
|
32
|
+
@success
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Administrate
|
|
4
|
+
module MCP
|
|
5
|
+
module Actions
|
|
6
|
+
# Reads the `mcp_data` of an action's result and turns it into what goes back to the client: a
|
|
7
|
+
# copy built only from plain Hashes with String keys, Arrays, Strings and JSON scalars, no deeper
|
|
8
|
+
# than MAX_DEPTH and no larger than `config.action_data_max_bytes` once encoded. The copy, not
|
|
9
|
+
# the host's objects, is what gets encoded, so no `as_json` of theirs runs. The action has
|
|
10
|
+
# already run when this is checked, so the error says so.
|
|
11
|
+
module ResultData
|
|
12
|
+
MAX_DEPTH = 32
|
|
13
|
+
|
|
14
|
+
SCALARS = [Integer, TrueClass, FalseClass, NilClass].freeze
|
|
15
|
+
|
|
16
|
+
class << self
|
|
17
|
+
def extract!(result, tool_name:)
|
|
18
|
+
return nil unless result.respond_to?(:mcp_data)
|
|
19
|
+
|
|
20
|
+
data = result.mcp_data
|
|
21
|
+
return nil if data.nil?
|
|
22
|
+
|
|
23
|
+
normalize_root!(data, tool_name)
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
private
|
|
27
|
+
|
|
28
|
+
def normalize_root!(data, tool_name)
|
|
29
|
+
raise TypeError, "data (#{data.class}) is not a Hash" unless data.is_a?(Hash)
|
|
30
|
+
|
|
31
|
+
normalize!(data, 'data').tap { |copy| check_size!(copy) }
|
|
32
|
+
rescue TypeError, RangeError => e
|
|
33
|
+
raise Error, "#{tool_name} ran, but its data cannot be returned: #{e.message}"
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def normalize!(value, path, depth = 0)
|
|
37
|
+
raise RangeError, "#{path} is nested deeper than #{MAX_DEPTH} levels" if depth > MAX_DEPTH
|
|
38
|
+
|
|
39
|
+
case value
|
|
40
|
+
when Hash then normalize_hash!(value, path, depth)
|
|
41
|
+
when Array then value.each_with_index.map { |item, index| normalize!(item, "#{path}[#{index}]", depth + 1) }
|
|
42
|
+
when String, Symbol then normalize_string!(value, path)
|
|
43
|
+
else normalize_scalar!(value, path)
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def normalize_string!(value, path)
|
|
48
|
+
copy = String.new(value.to_s).encode(Encoding::UTF_8)
|
|
49
|
+
raise TypeError, "#{path} is not valid UTF-8" unless copy.valid_encoding?
|
|
50
|
+
|
|
51
|
+
copy
|
|
52
|
+
rescue EncodingError
|
|
53
|
+
raise TypeError, "#{path} cannot be converted to UTF-8"
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def normalize_hash!(hash, path, depth)
|
|
57
|
+
hash.each_with_object({}) do |(key, item), copy|
|
|
58
|
+
name = key_name!(key, path)
|
|
59
|
+
raise TypeError, "#{path} has the key #{name} twice" if copy.key?(name)
|
|
60
|
+
|
|
61
|
+
copy[name] = normalize!(item, "#{path}.#{name}", depth + 1)
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def key_name!(key, path)
|
|
66
|
+
return normalize_string!(key, "a key of #{path}") if key.is_a?(String) || key.is_a?(Symbol)
|
|
67
|
+
|
|
68
|
+
raise TypeError, "#{path} has a key (#{key.class}) that is not a String or Symbol"
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def normalize_scalar!(value, path)
|
|
72
|
+
if value.instance_of?(Float)
|
|
73
|
+
raise TypeError, "#{path} is not a finite number" unless value.finite?
|
|
74
|
+
|
|
75
|
+
return value
|
|
76
|
+
end
|
|
77
|
+
return value if SCALARS.any? { |type| value.instance_of?(type) }
|
|
78
|
+
|
|
79
|
+
raise TypeError, "#{path} (#{value.class}) is not a JSON value"
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def check_size!(copy)
|
|
83
|
+
limit = Administrate::MCP.config.action_data_max_bytes
|
|
84
|
+
return if limit.nil?
|
|
85
|
+
|
|
86
|
+
bytes = copy.to_json.bytesize
|
|
87
|
+
return if bytes <= limit
|
|
88
|
+
|
|
89
|
+
raise RangeError,
|
|
90
|
+
"data is #{bytes} bytes of JSON, over the #{limit}-byte limit (config.action_data_max_bytes)"
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
end
|
|
@@ -9,50 +9,68 @@ module Administrate
|
|
|
9
9
|
# declaration we build a tool whose name, input schema and description let non-developer users
|
|
10
10
|
# discover and call it through the protocol.
|
|
11
11
|
#
|
|
12
|
+
# An action is a member action by default: it takes an `id` and runs against the loaded record.
|
|
13
|
+
# Declared with `on: :collection`, it takes no `id`, loads nothing and runs against the model.
|
|
14
|
+
#
|
|
15
|
+
# An action declared with `uploads:` (true, a list of attachment attributes, or a hash of
|
|
16
|
+
# attribute to `content_types:` / `max_size:` overrides) also takes an optional
|
|
17
|
+
# `<attribute>_upload_id` for each of them. The id is resolved into the attachment value before
|
|
18
|
+
# the block runs, so the block sees `params[:<attribute>]`.
|
|
19
|
+
#
|
|
12
20
|
# Enforcement is layered: the generated tool requires an OAuth `write` scope (the rollout gate)
|
|
13
|
-
# AND runs the resource's authorization predicate against the loaded record
|
|
14
|
-
#
|
|
21
|
+
# AND runs the resource's authorization predicate against the loaded record, or against a new
|
|
22
|
+
# instance of the model for a collection action, as Administrate does for `new` and `create`.
|
|
23
|
+
# Auditing is inherited from BaseTool.
|
|
15
24
|
module Actions
|
|
16
25
|
Definition =
|
|
17
26
|
Struct.new(
|
|
18
27
|
:model_class,
|
|
19
28
|
:name,
|
|
29
|
+
:on,
|
|
20
30
|
:predicate,
|
|
21
31
|
:scope,
|
|
22
32
|
:destructive,
|
|
23
33
|
:description,
|
|
24
34
|
:params,
|
|
25
35
|
:required,
|
|
36
|
+
:uploads,
|
|
26
37
|
:invoke,
|
|
27
38
|
keyword_init: true
|
|
28
39
|
)
|
|
29
40
|
|
|
30
41
|
RESERVED_PARAMS = %i[admin id].freeze
|
|
31
42
|
|
|
43
|
+
TARGETS = %i[member collection].freeze
|
|
44
|
+
|
|
32
45
|
class << self
|
|
33
46
|
# Normalizes the arguments of a `mcp_action` declaration into a spec (everything but the
|
|
34
47
|
# model, which is inferred from the owning dashboard when definitions are built).
|
|
35
|
-
def build_spec(name, description:, params: {}, predicate: nil, pundit: nil, scope: :write,
|
|
36
|
-
destructive: true, &invoke)
|
|
48
|
+
def build_spec(name, description:, on: :member, params: {}, predicate: nil, pundit: nil, scope: :write,
|
|
49
|
+
destructive: true, uploads: false, &invoke)
|
|
37
50
|
raise ArgumentError, "#{name}: a block is required to invoke the action" unless invoke
|
|
51
|
+
raise ArgumentError, "#{name}: on: must be :member or :collection" unless TARGETS.include?(on)
|
|
38
52
|
|
|
39
53
|
reject_reserved_params!(name, params)
|
|
40
54
|
normalized = normalize_params(params)
|
|
41
55
|
|
|
42
56
|
{
|
|
43
57
|
name: name.to_sym,
|
|
58
|
+
on:,
|
|
44
59
|
predicate: (predicate || pundit || :"#{name}?").to_sym,
|
|
45
60
|
scope: scope.to_sym,
|
|
46
61
|
destructive:,
|
|
47
62
|
description:,
|
|
48
63
|
params: normalized.transform_values { |spec| spec.except(:required) },
|
|
49
64
|
required: normalized.reject { |_, spec| spec[:required] == false }.keys,
|
|
65
|
+
uploads: Uploads::Declarations.normalize(uploads, action_name: name),
|
|
50
66
|
invoke:
|
|
51
67
|
}
|
|
52
68
|
end
|
|
53
69
|
|
|
54
70
|
def normalize_params(params)
|
|
55
|
-
params.
|
|
71
|
+
params.to_h do |name, spec|
|
|
72
|
+
[name.to_sym, spec.is_a?(String) ? { type: 'string', description: spec } : spec.to_h.symbolize_keys]
|
|
73
|
+
end
|
|
56
74
|
end
|
|
57
75
|
|
|
58
76
|
def definitions
|
|
@@ -61,11 +79,20 @@ module Administrate
|
|
|
61
79
|
next [] unless entry.dashboard_class.respond_to?(:mcp_action_specs)
|
|
62
80
|
|
|
63
81
|
entry.dashboard_class.mcp_action_specs.map do |spec|
|
|
64
|
-
|
|
82
|
+
uploads = Uploads::Declarations.action_attributes(entry.dashboard_class, spec[:name], spec[:uploads])
|
|
83
|
+
Definition.new(model_class: entry.model_class, **spec, uploads:)
|
|
65
84
|
end
|
|
66
85
|
end
|
|
67
86
|
end
|
|
68
87
|
|
|
88
|
+
def tool_name(definition)
|
|
89
|
+
"#{definition.model_class.name.underscore.tr('/', '_')}_#{definition.name}"
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def available_to?(admin, definition, scopes:)
|
|
93
|
+
scopes.map(&:to_sym).include?(definition.scope) && authorized_for_discovery?(admin, definition)
|
|
94
|
+
end
|
|
95
|
+
|
|
69
96
|
def all_tools
|
|
70
97
|
@all_tools ||= definitions.map { |defn| ToolFactory.build(defn) }
|
|
71
98
|
end
|
|
@@ -73,13 +100,8 @@ module Administrate
|
|
|
73
100
|
# Tool classes the caller may both see and run: write scope granted AND the authorization
|
|
74
101
|
# predicate satisfied at the role level. The actual call re-checks it against the record.
|
|
75
102
|
def tools_for(server_context)
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
all_tools.select do |tool|
|
|
80
|
-
defn = tool.definition
|
|
81
|
-
granted.include?(defn.scope) && authorized_for_discovery?(admin, defn)
|
|
82
|
-
end
|
|
103
|
+
scopes = server_context[:scopes] || []
|
|
104
|
+
all_tools.select { |tool| available_to?(server_context[:admin], tool.definition, scopes:) }
|
|
83
105
|
end
|
|
84
106
|
|
|
85
107
|
def reset!
|
|
@@ -106,7 +128,8 @@ module Administrate
|
|
|
106
128
|
end
|
|
107
129
|
|
|
108
130
|
def authorized_for_discovery?(admin, definition)
|
|
109
|
-
|
|
131
|
+
target = definition.on == :collection ? definition.model_class.new : definition.model_class
|
|
132
|
+
Administrate::MCP.config.authorization.authorized?(admin, target, definition.predicate)
|
|
110
133
|
rescue StandardError
|
|
111
134
|
false
|
|
112
135
|
end
|
|
@@ -126,7 +149,7 @@ module Administrate
|
|
|
126
149
|
def build(defn)
|
|
127
150
|
resource = defn.model_class.name.underscore
|
|
128
151
|
klass = Class.new(BaseTool)
|
|
129
|
-
klass.tool_name
|
|
152
|
+
klass.tool_name Actions.tool_name(defn)
|
|
130
153
|
klass.description defn.description
|
|
131
154
|
klass.annotations(read_only_hint: false, destructive_hint: defn.destructive, open_world_hint: true)
|
|
132
155
|
klass.requires_scope defn.scope
|
|
@@ -135,42 +158,70 @@ module Administrate
|
|
|
135
158
|
klass
|
|
136
159
|
end
|
|
137
160
|
|
|
161
|
+
private
|
|
162
|
+
|
|
138
163
|
def schema_for(defn, resource)
|
|
139
|
-
properties =
|
|
140
|
-
defn.
|
|
141
|
-
|
|
164
|
+
properties = defn.params.merge(Uploads::Declarations.param_schemas(defn))
|
|
165
|
+
required = defn.required.map(&:to_s)
|
|
166
|
+
if defn.on == :member
|
|
167
|
+
properties = { id: { type: 'string', description: "ID or slug of the #{resource}" }, **properties }
|
|
168
|
+
required = %w[id] + required
|
|
169
|
+
end
|
|
170
|
+
{ properties:, required:, additionalProperties: false }
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
def define_behaviors(klass, defn)
|
|
174
|
+
klass.define_singleton_method(:definition) { defn }
|
|
175
|
+
klass.define_singleton_method(:check_roles!) do |admin, id: nil, **|
|
|
176
|
+
ToolFactory.send(:authorize!, defn, admin, id)
|
|
177
|
+
end
|
|
178
|
+
klass.define_singleton_method(:execute) do |admin:, id: nil, **params|
|
|
179
|
+
outcome = ToolFactory.send(:invoke, defn, admin, id, params)
|
|
180
|
+
if outcome.key?(:error)
|
|
181
|
+
error_response(outcome[:error], data: outcome[:details])
|
|
182
|
+
else
|
|
183
|
+
json_response(outcome[:data], structured: true)
|
|
184
|
+
end
|
|
185
|
+
end
|
|
142
186
|
end
|
|
143
187
|
|
|
144
|
-
# Replaces the role-based default with instance-level authorization on the loaded record.
|
|
145
188
|
def authorize!(defn, admin, id)
|
|
146
|
-
|
|
147
|
-
Actions.authorize!(admin,
|
|
189
|
+
target = defn.on == :member ? Actions.find_record!(defn.model_class, id) : defn.model_class.new
|
|
190
|
+
Actions.authorize!(admin, target, defn.predicate)
|
|
148
191
|
end
|
|
149
192
|
|
|
150
193
|
def invoke(defn, admin, id, params)
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
194
|
+
declared = params.slice(*defn.params.keys, *Uploads::Declarations.param_schemas(defn).keys)
|
|
195
|
+
arguments = { admin:, params: Uploads::Declarations.resolve_params(defn, admin, declared) }
|
|
196
|
+
arguments[:record] = Actions.find_record!(defn.model_class, id) if defn.on == :member
|
|
197
|
+
returned = defn.invoke.call(**arguments)
|
|
198
|
+
result = returned.is_a?(ActionResult) ? returned.record : returned
|
|
199
|
+
data = ResultData.extract!(returned, tool_name: Actions.tool_name(defn))
|
|
200
|
+
failures = [returned, result].select { |candidate| failed?(candidate) }
|
|
201
|
+
unless failures.empty?
|
|
202
|
+
return { error: failure_message(defn, failures.first, arguments[:record]), details: data }
|
|
203
|
+
end
|
|
154
204
|
|
|
155
|
-
{ data:
|
|
205
|
+
{ data: success_data(defn, id, result, data) }
|
|
156
206
|
end
|
|
157
207
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
klass.define_singleton_method(:definition) { defn }
|
|
162
|
-
klass.define_singleton_method(:check_roles!) do |admin, id: nil, **|
|
|
163
|
-
ToolFactory.authorize!(defn, admin, id)
|
|
164
|
-
end
|
|
165
|
-
klass.define_singleton_method(:execute) do |admin:, id:, **params|
|
|
166
|
-
outcome = ToolFactory.invoke(defn, admin, id, params)
|
|
167
|
-
outcome.key?(:error) ? error_response(outcome[:error]) : json_response(outcome[:data])
|
|
168
|
-
end
|
|
208
|
+
def success_data(defn, id, result, data)
|
|
209
|
+
id = result.id if defn.on == :collection && result.is_a?(ActiveRecord::Base)
|
|
210
|
+
{ status: 'ok', model: defn.model_class.name.underscore, id:, action: defn.name.to_s, data: }.compact
|
|
169
211
|
end
|
|
170
212
|
|
|
171
213
|
def failed?(result)
|
|
214
|
+
return true if result == false
|
|
215
|
+
return result.new_record? || result.errors.any? if result.is_a?(ActiveRecord::Base)
|
|
216
|
+
|
|
172
217
|
result.respond_to?(:success?) && !result.success?
|
|
173
218
|
end
|
|
219
|
+
|
|
220
|
+
def failure_message(defn, result, record)
|
|
221
|
+
invalid = result.is_a?(ActiveRecord::Base) ? result : (record if result == false)
|
|
222
|
+
message = invalid ? invalid.errors.full_messages.to_sentence : result.try(:error)
|
|
223
|
+
message.presence || "#{defn.name} failed"
|
|
224
|
+
end
|
|
174
225
|
end
|
|
175
226
|
end
|
|
176
227
|
end
|
|
@@ -55,7 +55,11 @@ module Administrate
|
|
|
55
55
|
check_roles!(admin, **args)
|
|
56
56
|
audit!(admin, args, server_context)
|
|
57
57
|
reject_reserved_arguments!(args)
|
|
58
|
-
execute(**args, admin
|
|
58
|
+
execute(**args, admin:, **execute_context(server_context))
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def execute_context(_server_context)
|
|
62
|
+
{}
|
|
59
63
|
end
|
|
60
64
|
|
|
61
65
|
def reject_reserved_arguments!(args)
|
|
@@ -102,12 +106,17 @@ module Administrate
|
|
|
102
106
|
::MCP::Tool::Response.new([{ type: 'text', text: }])
|
|
103
107
|
end
|
|
104
108
|
|
|
105
|
-
def json_response(data)
|
|
106
|
-
::MCP::Tool::Response.new([{ type: 'text', text: data.to_json }])
|
|
109
|
+
def json_response(data, structured: false)
|
|
110
|
+
::MCP::Tool::Response.new([{ type: 'text', text: data.to_json }], structured_content: (data if structured))
|
|
107
111
|
end
|
|
108
112
|
|
|
109
|
-
def error_response(message)
|
|
110
|
-
|
|
113
|
+
def error_response(message, data: nil)
|
|
114
|
+
content = [{ type: 'text', text: message }]
|
|
115
|
+
return ::MCP::Tool::Response.new(content, error: true) if data.nil?
|
|
116
|
+
|
|
117
|
+
structured = { error: message, data: }
|
|
118
|
+
content << { type: 'text', text: structured.to_json }
|
|
119
|
+
::MCP::Tool::Response.new(content, error: true, structured_content: structured)
|
|
111
120
|
end
|
|
112
121
|
end
|
|
113
122
|
end
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Administrate
|
|
4
|
+
module MCP
|
|
5
|
+
# Removes upload batches that expired before the given cutoff, one batch at a time. The caller
|
|
6
|
+
# decides whether to run the next batch: `call` reports whether the batch was full. The
|
|
7
|
+
# uploaded objects are left to the bucket's own lifecycle rule.
|
|
8
|
+
class CleanExpiredUploadBatches
|
|
9
|
+
BATCH_SIZE = 10_000
|
|
10
|
+
|
|
11
|
+
Result = Struct.new(:deleted_count, :more?, keyword_init: true)
|
|
12
|
+
|
|
13
|
+
def self.call(...)
|
|
14
|
+
new(...).call
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def initialize(till: Time.current)
|
|
18
|
+
@till = till
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def call
|
|
22
|
+
deleted_count = UploadBatch.expired(@till).limit(BATCH_SIZE).delete_all
|
|
23
|
+
Result.new(deleted_count:, more?: deleted_count == BATCH_SIZE)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
@@ -119,6 +119,10 @@ module Administrate
|
|
|
119
119
|
matches?(field_class, Administrate::MCP.config.has_many_field_classes)
|
|
120
120
|
end
|
|
121
121
|
|
|
122
|
+
def serializer_for(field_spec)
|
|
123
|
+
lookup_serializer(resolve_field_class(field_spec))
|
|
124
|
+
end
|
|
125
|
+
|
|
122
126
|
def resolve_field_class(field_spec)
|
|
123
127
|
case field_spec
|
|
124
128
|
when Administrate::Field::Deferred
|
|
@@ -16,6 +16,8 @@ module Administrate
|
|
|
16
16
|
|
|
17
17
|
SIDEKIQ_STATS_TOOL = 'Administrate::MCP::Tools::SidekiqStats'
|
|
18
18
|
|
|
19
|
+
UPLOADS_PREPARE_TOOL = 'Administrate::MCP::Tools::UploadsPrepare'
|
|
20
|
+
|
|
19
21
|
class << self
|
|
20
22
|
def build(server_context:)
|
|
21
23
|
server_context[:authorization_errors] ||= []
|
|
@@ -46,12 +48,16 @@ module Administrate
|
|
|
46
48
|
|
|
47
49
|
def discover_tools(server_context)
|
|
48
50
|
load_host_tools
|
|
49
|
-
|
|
51
|
+
action_tools = Actions.tools_for(server_context)
|
|
52
|
+
built_in = built_in_tools
|
|
53
|
+
built_in -= [Tools::UploadsPrepare] unless Uploads::Declarations.any?(action_tools)
|
|
54
|
+
(built_in + host_tools).uniq + action_tools
|
|
50
55
|
end
|
|
51
56
|
|
|
52
57
|
def built_in_tools
|
|
53
58
|
names = BUILT_IN_TOOLS.dup
|
|
54
59
|
names << REPORT_IMPROVEMENT_TOOL if Administrate::MCP.config.feedback_tool
|
|
60
|
+
names << UPLOADS_PREPARE_TOOL if Administrate::MCP.config.uploads.enabled
|
|
55
61
|
names << SIDEKIQ_RETRIES_TOOL if defined?(::Sidekiq)
|
|
56
62
|
names << SIDEKIQ_STATS_TOOL if defined?(::Sidekiq) && Administrate::MCP.config.sidekiq_stats_provider
|
|
57
63
|
names.filter_map(&:safe_constantize)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Administrate
|
|
4
|
+
module MCP
|
|
5
|
+
module Tools
|
|
6
|
+
# Hands out presigned upload URLs for one attachment attribute of one action, so a client can
|
|
7
|
+
# upload a file and then pass its upload_id to that action. Published only when uploads are
|
|
8
|
+
# enabled and the caller has an action that accepts uploads.
|
|
9
|
+
class UploadsPrepare < BaseTool
|
|
10
|
+
tool_name 'uploads_prepare'
|
|
11
|
+
requires_scope :write
|
|
12
|
+
description 'Prepare file uploads for an action that accepts them. Pass the action\'s `tool` name, the ' \
|
|
13
|
+
'`attribute` the files are for (the action takes `<attribute>_upload_id`), and `files` as an ' \
|
|
14
|
+
'object of filename to size in bytes. Each file gets an `upload_id`, a `method`, a `url` and ' \
|
|
15
|
+
'either `fields` or `headers`. For `POST`, send a multipart form to `url` with every entry of ' \
|
|
16
|
+
'`fields` followed by the file as `file`, for example ' \
|
|
17
|
+
'`curl -F key=... -F policy=... (one -F per field) -F file=@logo.png "<url>"`. For `PUT`, ' \
|
|
18
|
+
'send the file as the body with every header in `headers`. Then pass the `upload_id` as ' \
|
|
19
|
+
'`<attribute>_upload_id` to that action. URLs expire after 15 minutes by default and upload ' \
|
|
20
|
+
'ids after an hour.'
|
|
21
|
+
annotations(read_only_hint: false, destructive_hint: false, open_world_hint: true)
|
|
22
|
+
|
|
23
|
+
input_schema(
|
|
24
|
+
properties: {
|
|
25
|
+
tool: { type: 'string', description: 'The action tool the files are for, for example widget_update.' },
|
|
26
|
+
attribute: { type: 'string', description: 'The attachment attribute, for example picture.' },
|
|
27
|
+
files: {
|
|
28
|
+
type: 'object',
|
|
29
|
+
description: 'Filename to size in bytes, for example {"logo.png": 48213}.',
|
|
30
|
+
additionalProperties: { type: 'integer' }
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
required: %w[tool attribute files],
|
|
34
|
+
additionalProperties: false
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
def self.execute(admin:, scopes:, tool:, attribute:, files:)
|
|
38
|
+
json_response(Administrate::MCP::Uploads.prepare(admin:, scopes:, tool:, attribute:, files:))
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def self.execute_context(server_context)
|
|
42
|
+
{ scopes: server_context[:scopes] || [] }
|
|
43
|
+
end
|
|
44
|
+
private_class_method :execute_context
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|