administrate-mcp 0.4.0 → 0.6.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.
Files changed (30) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +49 -1
  3. data/README.md +12 -0
  4. data/app/lib/administrate/mcp/action_result.rb +36 -0
  5. data/app/lib/administrate/mcp/actions/result_data.rb +96 -0
  6. data/app/lib/administrate/mcp/actions.rb +24 -7
  7. data/app/lib/administrate/mcp/base_tool.rb +32 -4
  8. data/app/lib/administrate/mcp/feedback_categories.rb +2 -1
  9. data/app/lib/administrate/mcp/server_builder.rb +10 -1
  10. data/app/lib/administrate/mcp/tool_view.rb +125 -0
  11. data/app/lib/administrate/mcp/tool_views/field_hints.rb +78 -0
  12. data/app/lib/administrate/mcp/tool_views/resource_view.rb +17 -0
  13. data/app/lib/administrate/mcp/tool_views/sidekiq_view.rb +17 -0
  14. data/app/lib/administrate/mcp/tools/admin_resource_list.rb +4 -1
  15. data/app/lib/administrate/mcp/tools/admin_resource_show.rb +11 -4
  16. data/app/lib/administrate/mcp/tools/report_improvement.rb +2 -1
  17. data/app/lib/administrate/mcp/tools/sidekiq_retries.rb +1 -0
  18. data/app/lib/administrate/mcp/tools/sidekiq_stats.rb +1 -0
  19. data/docs/configuration.md +5 -0
  20. data/docs/dashboards.md +60 -1
  21. data/docs/tool-views.md +135 -0
  22. data/lib/administrate/mcp/configuration.rb +6 -0
  23. data/lib/administrate/mcp/tool_views/resource.css +25 -0
  24. data/lib/administrate/mcp/tool_views/resource.js +384 -0
  25. data/lib/administrate/mcp/tool_views/runtime.css +112 -0
  26. data/lib/administrate/mcp/tool_views/runtime.js +296 -0
  27. data/lib/administrate/mcp/tool_views/sidekiq.css +6 -0
  28. data/lib/administrate/mcp/tool_views/sidekiq.js +108 -0
  29. data/lib/administrate/mcp/version.rb +1 -1
  30. metadata +14 -1
@@ -16,6 +16,7 @@ module Administrate
16
16
  description 'Search and list admin resources. ' \
17
17
  'Supports text search, filters, sorting, field selection, and HasMany expansion.'
18
18
  annotations read_only_hint: true, destructive_hint: false, open_world_hint: true
19
+ tool_view 'Administrate::MCP::ToolViews::ResourceView'
19
20
 
20
21
  input_schema(
21
22
  properties: {
@@ -103,7 +104,9 @@ module Administrate
103
104
  scope = apply_sort(scope, dashboard, sort, sort_direction)
104
105
  records = scope.page(page).per(per_page)
105
106
 
106
- json_response(build_response(records, dashboard, page, per_page, fields:, expand:))
107
+ response = build_response(records, dashboard, page, per_page, fields:, expand:)
108
+ columns = response[:columns].drop(1).map(&:to_sym)
109
+ json_response(response, meta: ToolViews::FieldHints.meta(entry, dashboard, columns, admin:))
107
110
  end
108
111
 
109
112
  def self.build_response(records, dashboard, page, per_page, fields: nil, expand: nil)
@@ -16,6 +16,7 @@ module Administrate
16
16
  description 'Show admin resource(s) by ID or slug. ' \
17
17
  'Accepts a single ID or an array of up to 10 IDs for batch lookup.'
18
18
  annotations read_only_hint: true, destructive_hint: false, open_world_hint: true
19
+ tool_view 'Administrate::MCP::ToolViews::ResourceView'
19
20
 
20
21
  input_schema(
21
22
  properties: {
@@ -78,19 +79,22 @@ module Administrate
78
79
  attrs, expand_set =
79
80
  resolve_attributes_and_expansions(dashboard, fields, expand, :show_page_attributes, MAX_EXPAND)
80
81
 
81
- return batch_show(entry, dashboard, id, resource, attributes: attrs, expand: expand_set) if id.is_a?(Array)
82
+ if id.is_a?(Array)
83
+ return batch_show(entry, dashboard, id, resource, attributes: attrs, expand: expand_set, admin:)
84
+ end
82
85
 
83
86
  record = find_record(entry, id)
84
87
  return error_response("#{resource.capitalize} not found for: #{id}") unless record
85
88
 
86
89
  json_response(
87
- FieldSerializer.serialize(record, dashboard, attributes: attrs, expand: expand_set, resolve_getters: true)
90
+ FieldSerializer.serialize(record, dashboard, attributes: attrs, expand: expand_set, resolve_getters: true),
91
+ meta: ToolViews::FieldHints.meta(entry, dashboard, attrs, admin:)
88
92
  )
89
93
  end
90
94
 
91
95
  # Getters stay unresolved here: they are per-record work, and a batch multiplies them by up
92
96
  # to MAX_BATCH. Read one id at a time when a getter-backed attribute matters.
93
- def self.batch_show(entry, dashboard, ids, resource, attributes:, expand:)
97
+ def self.batch_show(entry, dashboard, ids, resource, attributes:, expand:, admin:)
94
98
  reject_over_limit!('ids', ids.size, MAX_BATCH)
95
99
  columns = FieldSerializer.resolve_columns(dashboard, attributes)
96
100
 
@@ -105,7 +109,10 @@ module Administrate
105
109
  end
106
110
  end
107
111
 
108
- json_response({ columns: %w[url] + columns.map(&:to_s), rows: })
112
+ json_response(
113
+ { columns: %w[url] + columns.map(&:to_s), rows: },
114
+ meta: ToolViews::FieldHints.meta(entry, dashboard, columns, admin:)
115
+ )
109
116
  end
110
117
 
111
118
  def self.find_record(entry, id)
@@ -9,7 +9,8 @@ module Administrate
9
9
  tool_name 'report_mcp_improvement'
10
10
  requires_roles
11
11
  description 'Report an improvement for the MCP server (misleading description, missing filter, ' \
12
- 'bad serialization, missing resource, etc.).'
12
+ 'bad serialization, missing resource, etc.). Use missing_view when the person needed to ' \
13
+ 'browse, compare or act on a result and plain text was a poor fit for it.'
13
14
 
14
15
  input_schema(
15
16
  properties: {
@@ -11,6 +11,7 @@ module Administrate
11
11
  description 'Get the Sidekiq retry queue size and optionally the first page of retry entries ' \
12
12
  '(up to 25 jobs with class, error, retry count, and timestamps).'
13
13
  annotations read_only_hint: true, destructive_hint: false, open_world_hint: false
14
+ tool_view 'Administrate::MCP::ToolViews::SidekiqView'
14
15
 
15
16
  input_schema(
16
17
  properties: {
@@ -14,6 +14,7 @@ module Administrate
14
14
  'Returns retry breakdown and optionally per-queue breakdowns. ' \
15
15
  'Each breakdown maps job class names to their pending count.'
16
16
  annotations read_only_hint: true, destructive_hint: false, open_world_hint: false
17
+ tool_view 'Administrate::MCP::ToolViews::SidekiqView'
17
18
 
18
19
  input_schema(
19
20
  properties: {
@@ -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,14 @@ 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
+ | `tool_views` | `false` | Whether tools link to their [tool views](tool-views.md) and the server publishes them, for clients that support MCP Apps |
209
+ | `tool_view_csp` | `{}` | Origins a tool view may load from: `resource_domains`, `connect_domains`, `frame_domains`, `base_uri_domains`. See [Tool views](tool-views.md#images-and-other-external-content) |
205
210
  | `uploads` | disabled | Presigned uploads: `enabled`, `storage`, `allowed_content_types`, `max_size`, `max_files`, `url_ttl`, `batch_ttl`. See [Presigned uploads](uploads.md) |
206
211
 
207
212
  ## Authorization adapters
data/docs/dashboards.md CHANGED
@@ -53,7 +53,8 @@ base class, is not applied to every resource. A subclass that wants one declares
53
53
  saved or has errors is an error too, with its validation messages. So is `false`, the result of
54
54
  a failed `update` or of a `destroy` a callback aborted; for a member action the message is the
55
55
  loaded record's validation messages when it has any. Anything else is a success, including a
56
- record the block destroyed.
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).
57
58
  - The tool is announced as destructive unless the declaration says `destructive: false`. Clients
58
59
  may ask for confirmation before running a destructive tool, so set it on actions that only add
59
60
  or prepare something.
@@ -71,6 +72,64 @@ base class, is not applied to every resource. A subclass that wants one declares
71
72
  - `uploads:` (`true`, a list of attachment attributes, or per-attribute `content_types:` and
72
73
  `max_size:`) adds an optional `<attribute>_upload_id` param for each of them, and the block
73
74
  receives the uploaded file as `params[:<attribute>]`. See [Presigned uploads](uploads.md).
75
+ - Once `config.tool_views` is on, an MCP Apps client renders the action's result in the resource
76
+ view: the outcome, the returned data and the saved record. `view:` (an
77
+ `Administrate::MCP::ToolView` subclass or its name) picks another view. See
78
+ [Tool views](tool-views.md).
79
+
80
+ ## Returning data from an action
81
+
82
+ An action answers `{ status, model, id, action }` by default, as JSON text and, identically, as the
83
+ result's `structuredContent`. When the client needs more than that, such as what an import created
84
+ and what it skipped, the block returns an `Administrate::MCP::ActionResult` and the answer gains a
85
+ `data` key:
86
+
87
+ ```ruby
88
+ mcp_action :import_batch,
89
+ on: :collection,
90
+ description: 'Import orders from a marketplace export.',
91
+ params: { references: { type: 'array', items: { type: 'string' } } } do |admin:, params:|
92
+ report = Orders::ImportBatch.call!(references: params[:references], admin:)
93
+ next Administrate::MCP::ActionResult.failure('No order matched', data: { unknown: report.unknown }) if report.empty?
94
+
95
+ Administrate::MCP::ActionResult.success(record: report.batch,
96
+ data: { created: report.created.size, unknown: report.unknown })
97
+ end
98
+ ```
99
+
100
+ ```json
101
+ { "status": "ok", "model": "order", "id": 42, "action": "import_batch", "data": { "created": 3, "unknown": ["X-9"] } }
102
+ ```
103
+
104
+ - `ActionResult.success(record:, data:)`: `record` is optional and is checked as if the block had
105
+ returned it, so an unsaved or invalid record is still an error, and a collection action still
106
+ answers its `id`.
107
+ - `ActionResult.failure(message, data:)` is an error with `message`, or `<action> failed` without
108
+ one. The error's first content block stays the message alone. When there is data, a second block
109
+ carries `{ "error": message, "data": … }` as JSON, and the result's `structuredContent` carries the
110
+ same object, so clients that only read the content still see the data.
111
+ - These two are the only constructors. Any result object that answers `mcp_data` with a Hash works
112
+ the same way, so a host's own service result can carry its data without being wrapped; `success?`
113
+ and `error` are read from it as for any other result.
114
+ - A plain Hash returned by the block is not sent back, as before: data reaches the client only when
115
+ the block asks for it, never because a service happened to return a Hash.
116
+ - `data` must be a Hash of JSON values: Hashes with String or Symbol keys, Arrays, Strings, Symbols,
117
+ Integers, finite Floats, `true`, `false` and `nil`, nested at most 32 levels deep. Strings and
118
+ keys must be valid UTF-8 or convertible to it, so check bytes read from a file. Convert
119
+ anything else, such as a time (`at.iso8601`) or a record (`record.id`), yourself. The engine
120
+ encodes a plain copy it builds from those values, so an object's own `as_json` never runs, and a
121
+ key given both as a String and as a Symbol is refused rather than sent twice. The copy's JSON may
122
+ be at most `config.action_data_max_bytes` (32 KB by default; `nil` removes the limit), so that an
123
+ action cannot fill the client's context. Return counts and the few items the client must act on,
124
+ not every row.
125
+ - Data that breaks a rule is answered as an error naming the offending path, for example
126
+ `data.report.rows[1] (Object) is not a JSON value`. The block has already run by then, so the
127
+ message says the action ran: fix the action rather than retrying the call.
128
+ - `data` reaches the client as it is, without the protections fields get from
129
+ `skipped_field_classes` and the field serializers. Don't return secrets, tokens or credentials. A
130
+ download URL is a bearer credential that ends up in transcripts and client logs, so make it
131
+ short-lived. Strings that came from end users (names, notes, references) are untrusted text in the
132
+ model's context, as they are in any field.
74
133
 
75
134
  ## Search
76
135
 
@@ -0,0 +1,135 @@
1
+ # Tool views
2
+
3
+ A tool view is an interactive page an MCP client renders in place of a tool's raw result. The
4
+ engine implements the server side of the [MCP Apps extension](https://github.com/modelcontextprotocol/ext-apps)
5
+ (SEP-1865): a view is a `ui://` HTML resource, a tool names the view that renders it in its `_meta`,
6
+ and a client that supports the extension fetches the view with `resources/read` and shows it next
7
+ to the conversation. A client without the extension ignores all of it and reads the tool's text
8
+ result as before.
9
+
10
+ Views are off until the host turns them on:
11
+
12
+ ```ruby
13
+ Administrate::MCP.configure do |config|
14
+ config.tool_views = true
15
+ end
16
+ ```
17
+
18
+ Nothing a tool returns changes for the model: the text content stays the same. A view receives the
19
+ full result, including a `_meta` entry the host keeps out of the model's context.
20
+
21
+ ## Built-in views
22
+
23
+ | View | URI | Tools | What it does |
24
+ | --- | --- | --- | --- |
25
+ | Resource | `ui://<server-name>/resource` | `admin_resource_list`, `admin_resource_show`, every `mcp_action` | A table of records with paging, sorting and search, a record page, and links that follow `belongs_to` and `has_many` associations to other registered resources. For an action, a confirmation, the data the action returned, and the record it saved |
26
+ | Sidekiq | `ui://<server-name>/sidekiq` | `sidekiq_stats`, `sidekiq_retries` | Counts per job class and per queue, the first page of retries, and a refresh button |
27
+
28
+ `<server-name>` is `config.server_name` with underscores turned into dashes.
29
+
30
+ The resource view needs nothing from a dashboard. `admin_resource_list` and `admin_resource_show`
31
+ add, when views are on, a `_meta["administrate-mcp/view"]` entry to their result: the resource name
32
+ and, per returned field, its kind (`belongs_to`, `has_many`, `datetime`, `enum`, `attachment`, `url`,
33
+ `scalar`, ...) and, for an association to a registered resource, that resource's name and the
34
+ foreign key a filtered list of it takes. Paging, sorting, search and following an association are
35
+ ordinary `tools/call` requests the client makes on the view's behalf, so they go through the same
36
+ authentication, authorization and `on_tool_call` audit as a call the model makes. A client that does
37
+ not proxy tool calls gets a read-only table whose rows open the record's admin page.
38
+
39
+ An `mcp_action` renders in the resource view unless it declares `view:`. The view shows the
40
+ action's outcome and the data it returned, then loads the record whose `id` the answer carries with
41
+ `admin_resource_show`, so an uploaded picture or a computed field is on screen right after the write.
42
+ A failed action shows its error message.
43
+
44
+ When the person moves to another page of the view, the view tells the client which records are on
45
+ screen (`ui/update-model-context`), so the next answer is about what the person is looking at. It
46
+ names them by resource and id only. Record text such as a name, and the person's search terms, stay
47
+ out of it: a model reads that context as coming from the client, and record text is written by
48
+ whoever owns the record.
49
+
50
+ The field hints name an associated resource only when the caller can list it, as
51
+ `admin_resource_list_resources` does.
52
+
53
+ Only `Field::Url` fields, attachments and the record's own admin link become links. A text field
54
+ that happens to hold a URL stays text, as on the admin show page, since end users write many of
55
+ those fields.
56
+
57
+ ## Images and other external content
58
+
59
+ A client renders a view under a Content Security Policy that, by default, loads nothing from another
60
+ origin. An attachment field whose URL points at your storage shows as a link until the origin is
61
+ declared:
62
+
63
+ ```ruby
64
+ config.tool_view_csp = { resource_domains: ['https://uploads.example.com'] }
65
+ ```
66
+
67
+ The keys are `resource_domains` (images, media, fonts, stylesheets, scripts), `connect_domains`
68
+ (`fetch` and WebSocket), `frame_domains` and `base_uri_domains`. Any other key raises when a view is
69
+ read. The client may still refuse an origin.
70
+
71
+ ## A view of your own
72
+
73
+ A view is a subclass of `Administrate::MCP::ToolView` that names a script and, optionally, a
74
+ stylesheet:
75
+
76
+ ```ruby
77
+ # app/mcp_views/review_queue_view.rb
78
+ class ReviewQueueView < Administrate::MCP::ToolView
79
+ title 'Review queue'
80
+ description 'The open reviews, with approve and reject buttons.'
81
+ script Rails.root.join('app/mcp_views/review_queue.js')
82
+ stylesheet Rails.root.join('app/mcp_views/review_queue.css')
83
+ end
84
+ ```
85
+
86
+ The view's name, used in its URI, is the class name without `View`, underscored (`review_queue`);
87
+ `view_name 'queue'` overrides it.
88
+
89
+ Link a tool to it with `tool_view`, or an action with `view:`:
90
+
91
+ ```ruby
92
+ class ReviewQueueTool < Administrate::MCP::BaseTool
93
+ tool_name 'review_queue'
94
+ tool_view ReviewQueueView
95
+ end
96
+
97
+ mcp_action :approve, description: 'Approve a review.', view: 'ReviewQueueView' do |record:, **|
98
+ record.approve!
99
+ end
100
+ ```
101
+
102
+ `tool_view` takes `visibility: %i[app]` for a tool only the view calls, which a client that supports
103
+ the extension keeps out of the model's tool list. It is not access control: a client without the
104
+ extension lists and calls the tool like any other, so the tool must run every check a model call
105
+ would need, and it does, since it is an ordinary tool on the server.
106
+
107
+ The engine wraps the script in an HTML document with a shared runtime, `window.AdministrateMCP`:
108
+
109
+ | Member | Does |
110
+ | --- | --- |
111
+ | `connect()` | Runs the `ui/initialize` handshake. Call it once, after registering handlers |
112
+ | `on('input' \| 'result' \| 'cancelled' \| 'context' \| 'teardown', callback)` | Registers a handler; `input` and `result` replay the last value to a late handler |
113
+ | `resultData(result)` | The result's `structuredContent`, or its JSON text content parsed |
114
+ | `resultError(result)` | The error message of a failed result, or `null` |
115
+ | `resultMeta(result, key)` | One entry of the result's `_meta` |
116
+ | `callTool(name, args)` | Calls a tool on this server through the client |
117
+ | `canCallTools()` | Whether the client proxies tool calls |
118
+ | `toolName()` | The name of the tool whose result the view is showing, when the client says |
119
+ | `openLink(url)`, `sendMessage(text)`, `updateModelContext(text)`, `requestDisplayMode(mode)` | The extension's `ui/open-link`, `ui/message`, `ui/update-model-context` and `ui/request-display-mode` |
120
+ | `h(tag, attributes, ...children)`, `mount(node)`, `link(url, label)`, `message(text, className)`, `formatDate(value)` | DOM helpers that set text, never markup |
121
+
122
+ The runtime reports the view's size to the client as it changes, and applies the client's theme
123
+ and CSS variables. The stylesheet it ships defines `--am-*` custom properties from those variables,
124
+ with light and dark fallbacks, for a view's own stylesheet to use.
125
+
126
+ A view renders admin data. Build its DOM with `h` or `textContent`, never `innerHTML`, so a record
127
+ cannot inject markup into the page. `h` only attaches functions as event handlers, and drops an
128
+ `href`, `src` or other URL attribute that is not `http` or `https`; `openLink` refuses the same
129
+ URLs. Keep record text out of `updateModelContext` and `sendMessage`: refer to records by id.
130
+
131
+ ## Asking for a view
132
+
133
+ `report_mcp_improvement` has a `missing_view` category for a result the person needed to browse,
134
+ compare or act on, and that read badly as text. Reports in it are the list of views worth building
135
+ next.
@@ -59,6 +59,9 @@ module Administrate
59
59
  :persist_feedback,
60
60
  :feedback_tool,
61
61
  :sidekiq_stats_provider,
62
+ :action_data_max_bytes,
63
+ :tool_views,
64
+ :tool_view_csp,
62
65
  :admin_route_namespace,
63
66
  :admin_url_options,
64
67
  :skipped_field_classes,
@@ -102,7 +105,10 @@ module Administrate
102
105
  @persist_feedback = false
103
106
  @feedback_tool = true
104
107
  @sidekiq_stats_provider = nil
108
+ @action_data_max_bytes = 32_768
105
109
  @uploads = UploadsConfiguration.new
110
+ @tool_views = false
111
+ @tool_view_csp = {}
106
112
  end
107
113
 
108
114
  def assign_fields
@@ -0,0 +1,25 @@
1
+ dl.am-fields {
2
+ display: grid;
3
+ grid-template-columns: minmax(110px, max-content) 1fr;
4
+ gap: 6px 16px;
5
+ margin: 0;
6
+ }
7
+ dl.am-fields dt { color: var(--am-text-muted); }
8
+ dl.am-fields dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
9
+ dl.am-fields dd .am-table-wrap { margin-top: 6px; }
10
+
11
+ img.am-image {
12
+ display: block;
13
+ max-width: min(100%, 320px);
14
+ max-height: 240px;
15
+ border-radius: var(--am-radius);
16
+ border: 1px solid var(--am-border);
17
+ }
18
+ img.am-thumb { display: block; max-width: 48px; max-height: 48px; border-radius: 4px; }
19
+
20
+ .am-pager { justify-content: flex-end; margin: 10px 0 0; }
21
+
22
+ @media (max-width: 480px) {
23
+ dl.am-fields { grid-template-columns: 1fr; gap: 2px; }
24
+ dl.am-fields dd { margin-bottom: 8px; }
25
+ }