reactiveadmin 0.2.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 (260) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +88 -0
  3. data/LICENSE +21 -0
  4. data/README.md +81 -0
  5. data/app/assets/reactive_admin/bridge.js +89 -0
  6. data/app/controllers/reactive_admin/api_controller.rb +30 -0
  7. data/app/controllers/reactive_admin/client_errors_controller.rb +38 -0
  8. data/app/controllers/reactive_admin/manifest_controller.rb +10 -0
  9. data/app/controllers/reactive_admin/mcp_controller.rb +48 -0
  10. data/app/controllers/reactive_admin/openapi_controller.rb +13 -0
  11. data/app/controllers/reactive_admin/session_controller.rb +11 -0
  12. data/app/views/layouts/reactive_admin/embed.html.erb +30 -0
  13. data/lib/generators/reactiveadmin/install/install_generator.rb +341 -0
  14. data/lib/generators/reactiveadmin/install/templates/menu.rb.tt +25 -0
  15. data/lib/generators/reactiveadmin/install/templates/reactive_admin.rb.tt +53 -0
  16. data/lib/generators/reactiveadmin/install/templates/reactive_admin_annotated.rb.tt +110 -0
  17. data/lib/reactive_admin/aa/v3/controller.rb +76 -0
  18. data/lib/reactive_admin/aa/v3/forms.rb +29 -0
  19. data/lib/reactive_admin/aa/v3/inputs/filters/typeahead_input.rb +51 -0
  20. data/lib/reactive_admin/aa/v3/inputs/typeahead_input.rb +8 -0
  21. data/lib/reactive_admin/aa/v3/install.rb +36 -0
  22. data/lib/reactive_admin/aa/v3/menu.rb +67 -0
  23. data/lib/reactive_admin/aa/v3/presenters.rb +102 -0
  24. data/lib/reactive_admin/aa/v3/registry.rb +78 -0
  25. data/lib/reactive_admin/aa/v3/views.rb +63 -0
  26. data/lib/reactive_admin/aa/v3.rb +23 -0
  27. data/lib/reactive_admin/aa/v4.rb +59 -0
  28. data/lib/reactive_admin/aa.rb +46 -0
  29. data/lib/reactive_admin/action_items.rb +39 -0
  30. data/lib/reactive_admin/action_links.rb +197 -0
  31. data/lib/reactive_admin/action_safety.rb +19 -0
  32. data/lib/reactive_admin/actions.rb +95 -0
  33. data/lib/reactive_admin/api_errors.rb +116 -0
  34. data/lib/reactive_admin/api_fallback.rb +15 -0
  35. data/lib/reactive_admin/api_guards.rb +445 -0
  36. data/lib/reactive_admin/audit.rb +72 -0
  37. data/lib/reactive_admin/auth/guard.rb +68 -0
  38. data/lib/reactive_admin/auth/token_requests.rb +15 -0
  39. data/lib/reactive_admin/auth.rb +135 -0
  40. data/lib/reactive_admin/authorizer.rb +47 -0
  41. data/lib/reactive_admin/background_requests.rb +33 -0
  42. data/lib/reactive_admin/batch_actions.rb +57 -0
  43. data/lib/reactive_admin/choices.rb +289 -0
  44. data/lib/reactive_admin/client_error.rb +70 -0
  45. data/lib/reactive_admin/composite_keys.rb +12 -0
  46. data/lib/reactive_admin/configuration.rb +221 -0
  47. data/lib/reactive_admin/controller_extension.rb +229 -0
  48. data/lib/reactive_admin/csv_injection.rb +26 -0
  49. data/lib/reactive_admin/date_bound.rb +31 -0
  50. data/lib/reactive_admin/degradation.rb +72 -0
  51. data/lib/reactive_admin/diagnostics.rb +16 -0
  52. data/lib/reactive_admin/doctor.rb +466 -0
  53. data/lib/reactive_admin/dry_run.rb +147 -0
  54. data/lib/reactive_admin/dry_run_flag.rb +18 -0
  55. data/lib/reactive_admin/embed.rb +73 -0
  56. data/lib/reactive_admin/engine.rb +47 -0
  57. data/lib/reactive_admin/error_keys.rb +23 -0
  58. data/lib/reactive_admin/exposure.rb +86 -0
  59. data/lib/reactive_admin/filters.rb +165 -0
  60. data/lib/reactive_admin/fixtures/scrubber.rb +1075 -0
  61. data/lib/reactive_admin/fixtures.rb +161 -0
  62. data/lib/reactive_admin/form_content.rb +78 -0
  63. data/lib/reactive_admin/form_field.rb +279 -0
  64. data/lib/reactive_admin/form_has_many.rb +116 -0
  65. data/lib/reactive_admin/form_lock.rb +71 -0
  66. data/lib/reactive_admin/form_payload.rb +57 -0
  67. data/lib/reactive_admin/form_recorder.rb +192 -0
  68. data/lib/reactive_admin/form_schema.rb +160 -0
  69. data/lib/reactive_admin/frame.rb +97 -0
  70. data/lib/reactive_admin/html_nodes.rb +390 -0
  71. data/lib/reactive_admin/html_policy.rb +338 -0
  72. data/lib/reactive_admin/html_rich.rb +186 -0
  73. data/lib/reactive_admin/implicit_defaults.rb +102 -0
  74. data/lib/reactive_admin/index_options.rb +41 -0
  75. data/lib/reactive_admin/index_payload.rb +259 -0
  76. data/lib/reactive_admin/index_recorder.rb +115 -0
  77. data/lib/reactive_admin/index_views.rb +85 -0
  78. data/lib/reactive_admin/inline_style.rb +125 -0
  79. data/lib/reactive_admin/labels_payload.rb +34 -0
  80. data/lib/reactive_admin/ladder.rb +268 -0
  81. data/lib/reactive_admin/layout_classes.rb +167 -0
  82. data/lib/reactive_admin/legacy_inventory.rb +547 -0
  83. data/lib/reactive_admin/location.rb +22 -0
  84. data/lib/reactive_admin/lookup_audit.rb +30 -0
  85. data/lib/reactive_admin/lookup_payload.rb +41 -0
  86. data/lib/reactive_admin/manifest.rb +36 -0
  87. data/lib/reactive_admin/masked_json.rb +62 -0
  88. data/lib/reactive_admin/masking.rb +100 -0
  89. data/lib/reactive_admin/mcp/access.rb +111 -0
  90. data/lib/reactive_admin/mcp/api.rb +123 -0
  91. data/lib/reactive_admin/mcp/count_tool.rb +22 -0
  92. data/lib/reactive_admin/mcp/layout.rb +175 -0
  93. data/lib/reactive_admin/mcp/output.rb +46 -0
  94. data/lib/reactive_admin/mcp/prompts.rb +111 -0
  95. data/lib/reactive_admin/mcp/server.rb +134 -0
  96. data/lib/reactive_admin/mcp/shapes.rb +164 -0
  97. data/lib/reactive_admin/mcp/tools.rb +386 -0
  98. data/lib/reactive_admin/mcp.rb +53 -0
  99. data/lib/reactive_admin/media_nodes.rb +34 -0
  100. data/lib/reactive_admin/menu.rb +90 -0
  101. data/lib/reactive_admin/menu_overlay.rb +291 -0
  102. data/lib/reactive_admin/node_registry.rb +47 -0
  103. data/lib/reactive_admin/open_api/builder.rb +156 -0
  104. data/lib/reactive_admin/open_api/context.rb +46 -0
  105. data/lib/reactive_admin/open_api/core.rb +51 -0
  106. data/lib/reactive_admin/open_api/operation_ids.rb +18 -0
  107. data/lib/reactive_admin/open_api/page_doc.rb +75 -0
  108. data/lib/reactive_admin/open_api/parts.rb +86 -0
  109. data/lib/reactive_admin/open_api/resource_doc.rb +423 -0
  110. data/lib/reactive_admin/open_api/security.rb +55 -0
  111. data/lib/reactive_admin/open_api/write_schema.rb +104 -0
  112. data/lib/reactive_admin/open_api.rb +41 -0
  113. data/lib/reactive_admin/option_source.rb +36 -0
  114. data/lib/reactive_admin/option_sources.rb +14 -0
  115. data/lib/reactive_admin/options_payload.rb +61 -0
  116. data/lib/reactive_admin/page_controller_extension.rb +112 -0
  117. data/lib/reactive_admin/page_forms.rb +181 -0
  118. data/lib/reactive_admin/page_payload.rb +120 -0
  119. data/lib/reactive_admin/param_normalizer.rb +89 -0
  120. data/lib/reactive_admin/paths.rb +63 -0
  121. data/lib/reactive_admin/permissions.rb +31 -0
  122. data/lib/reactive_admin/provenance.rb +57 -0
  123. data/lib/reactive_admin/query_guard.rb +108 -0
  124. data/lib/reactive_admin/ransack_guard.rb +107 -0
  125. data/lib/reactive_admin/rate_limit.rb +59 -0
  126. data/lib/reactive_admin/reactive_dsl.rb +99 -0
  127. data/lib/reactive_admin/readiness.rb +189 -0
  128. data/lib/reactive_admin/registry.rb +69 -0
  129. data/lib/reactive_admin/resource_meta.rb +120 -0
  130. data/lib/reactive_admin/resource_summary.rb +41 -0
  131. data/lib/reactive_admin/routes.rb +60 -0
  132. data/lib/reactive_admin/row_errors.rb +29 -0
  133. data/lib/reactive_admin/rspec.rb +116 -0
  134. data/lib/reactive_admin/scrubbed_error.rb +22 -0
  135. data/lib/reactive_admin/search.rb +79 -0
  136. data/lib/reactive_admin/server_timing.rb +31 -0
  137. data/lib/reactive_admin/show_payload.rb +88 -0
  138. data/lib/reactive_admin/sidebars.rb +34 -0
  139. data/lib/reactive_admin/site.rb +55 -0
  140. data/lib/reactive_admin/style_report.rb +129 -0
  141. data/lib/reactive_admin/style_sources.rb +83 -0
  142. data/lib/reactive_admin/template_actions.rb +126 -0
  143. data/lib/reactive_admin/template_content.rb +49 -0
  144. data/lib/reactive_admin/template_form.rb +442 -0
  145. data/lib/reactive_admin/test_support.rb +31 -0
  146. data/lib/reactive_admin/typeahead.rb +33 -0
  147. data/lib/reactive_admin/ui/assets.rb +91 -0
  148. data/lib/reactive_admin/ui/client_build.rb +47 -0
  149. data/lib/reactive_admin/ui/helper.rb +24 -0
  150. data/lib/reactive_admin/ui/packaged_client.rb +67 -0
  151. data/lib/reactive_admin/ui/shell.rb +81 -0
  152. data/lib/reactive_admin/ui/switch.rb +38 -0
  153. data/lib/reactive_admin/ui.rb +43 -0
  154. data/lib/reactive_admin/value_payload.rb +147 -0
  155. data/lib/reactive_admin/value_token.rb +36 -0
  156. data/lib/reactive_admin/values.rb +43 -0
  157. data/lib/reactive_admin/version.rb +3 -0
  158. data/lib/reactive_admin/write_audit.rb +60 -0
  159. data/lib/reactive_admin/write_guards.rb +142 -0
  160. data/lib/reactive_admin.rb +153 -0
  161. data/lib/reactiveadmin.rb +1 -0
  162. data/lib/tasks/reactiveadmin.rake +36 -0
  163. data/lib/tasks/reactiveadmin_client.rake +11 -0
  164. data/lib/tasks/reactiveadmin_legacy.rake +7 -0
  165. data/lib/tasks/reactiveadmin_styles.rake +6 -0
  166. data/openapi/core.yaml +1643 -0
  167. data/vendor/client/assets/ActionPage-XUYorI8E.js +1 -0
  168. data/vendor/client/assets/ActionView-BsZFcsgp.js +1 -0
  169. data/vendor/client/assets/CommandPalette-C59HT1ip.js +1 -0
  170. data/vendor/client/assets/DatePicker-DuaK0iMg.js +1 -0
  171. data/vendor/client/assets/DateRangeCalendar-B2BDsG-X.js +1 -0
  172. data/vendor/client/assets/DegradedNotice-DiH5n2DO.js +1 -0
  173. data/vendor/client/assets/FormDialog-pmYl8Eov.js +1 -0
  174. data/vendor/client/assets/FormSkeleton-DuSBZO3C.js +1 -0
  175. data/vendor/client/assets/FrameView-2X8cFvUt.css +1 -0
  176. data/vendor/client/assets/FrameView-zmUeDO8d.js +1 -0
  177. data/vendor/client/assets/GroupOverview-DI5T3k5K.js +1 -0
  178. data/vendor/client/assets/InlineForm-CMEIMgeh.js +1 -0
  179. data/vendor/client/assets/JsonDiff-o7JWr7CH.js +3 -0
  180. data/vendor/client/assets/JsonEditor-D4VXdlEx.js +1 -0
  181. data/vendor/client/assets/JsonView-BrJLDmSN.js +1 -0
  182. data/vendor/client/assets/MobileMenu-GAeFOeEb.js +1 -0
  183. data/vendor/client/assets/Node-SQl61V4K.js +2 -0
  184. data/vendor/client/assets/PageView-C-laNEPZ.js +1 -0
  185. data/vendor/client/assets/ResourceForm-BPjsoCY6.js +1 -0
  186. data/vendor/client/assets/ResourceIndex-COezAw5t.js +3 -0
  187. data/vendor/client/assets/ResourceOrPage-CRZGCY84.js +1 -0
  188. data/vendor/client/assets/ResourceShow-DweRXn18.js +1 -0
  189. data/vendor/client/assets/Segmented-BE9TCbph.js +1 -0
  190. data/vendor/client/assets/Sidebars-CsB9rFqX.js +1 -0
  191. data/vendor/client/assets/breadcrumb-DSA3Tlyd.js +1 -0
  192. data/vendor/client/assets/button-CvZ4_DFC.js +1 -0
  193. data/vendor/client/assets/calendar-BoyMpJIf.js +1 -0
  194. data/vendor/client/assets/check-C5A3J16N.js +1 -0
  195. data/vendor/client/assets/command-CMuk0oAt.js +1 -0
  196. data/vendor/client/assets/dist-CqEI82S_.js +1 -0
  197. data/vendor/client/assets/dist-IW4yX942.js +1 -0
  198. data/vendor/client/assets/editor-yqRLzgsJ.js +2 -0
  199. data/vendor/client/assets/external-link-C2aR4slL.js +1 -0
  200. data/vendor/client/assets/frames-C9gPCc3N.js +1 -0
  201. data/vendor/client/assets/humanize-DtU_Kpr4.js +1 -0
  202. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  203. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  204. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  205. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  206. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  207. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  208. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  209. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  210. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  211. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  212. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  213. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  214. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  215. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  216. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  217. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  218. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  219. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  220. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  221. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  222. data/vendor/client/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
  223. data/vendor/client/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
  224. data/vendor/client/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
  225. data/vendor/client/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
  226. data/vendor/client/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
  227. data/vendor/client/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
  228. data/vendor/client/assets/index-B51aUaAY.js +43 -0
  229. data/vendor/client/assets/index-Cs9rCoWM.css +2 -0
  230. data/vendor/client/assets/input-DByFmQPa.js +1 -0
  231. data/vendor/client/assets/json-De3PN-R6.css +1 -0
  232. data/vendor/client/assets/json-oTp7Q-d-.js +5 -0
  233. data/vendor/client/assets/media-D4a_En8R.js +1 -0
  234. data/vendor/client/assets/plus-CfJ9vo8X.js +1 -0
  235. data/vendor/client/assets/popover-CDtI9R8Q.js +1 -0
  236. data/vendor/client/assets/purify-G7QKJyJq.js +1 -0
  237. data/vendor/client/assets/query-CCsZN2fa.js +1 -0
  238. data/vendor/client/assets/recent-BrzLwL0D.js +1 -0
  239. data/vendor/client/assets/rich-BQc_q5T7.js +1 -0
  240. data/vendor/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  241. data/vendor/client/assets/select-C43qDA3k.js +1 -0
  242. data/vendor/client/assets/sheet-BPl2n-4n.js +1 -0
  243. data/vendor/client/assets/textarea-BnOphXry.js +1 -0
  244. data/vendor/client/assets/uiMode-z0ZbRV49.js +1 -0
  245. data/vendor/client/assets/uiToggle-DwnRQTH1.js +1 -0
  246. data/vendor/client/assets/useRecordForm-X_DExEP2.js +1 -0
  247. data/vendor/client/assets/useRecordVisit-BRtfMi-q.js +1 -0
  248. data/vendor/client/assets/utils-DwBGbDkG.js +1 -0
  249. data/vendor/client/assets/vendor-calendar-nTZiq9oY.js +1 -0
  250. data/vendor/client/assets/vendor-datefns-BoC6MCnl.js +1 -0
  251. data/vendor/client/assets/vendor-forms-D0h8hG_S.js +55 -0
  252. data/vendor/client/assets/vendor-purify-BXoPR7WT.js +3 -0
  253. data/vendor/client/assets/vendor-query-DZ6APRNI.js +1 -0
  254. data/vendor/client/assets/vendor-react-C1iE8mnY.js +9 -0
  255. data/vendor/client/assets/vendor-router-CI6Vh4k_.js +1 -0
  256. data/vendor/client/assets/vendor-table-DuQ835by.js +4 -0
  257. data/vendor/client/index.html +24 -0
  258. data/vendor/client/manifest.json +867 -0
  259. data/vendor/client/reactiveadmin-client.json +4 -0
  260. metadata +350 -0
@@ -0,0 +1,62 @@
1
+ module ReactiveAdmin
2
+ # A json value loaded for editing shows `[masked]` where a masked key holds a secret. A submitted
3
+ # placeholder takes the stored value of the same key back; one with nothing to restore is dropped,
4
+ # so the literal is never written.
5
+ module MaskedJson
6
+ module_function
7
+
8
+ # Top-level json fields only: values inside has_many rows are never loaded for editing.
9
+ def restore(params, fields, record, config)
10
+ fields.each do |field|
11
+ next unless field[:control] == "json" && field[:param]
12
+
13
+ *path, leaf = field[:param].scan(/[^\[\]]+/)
14
+ parent = path.inject(params) { |memo, key| memo.try(:[], key) }
15
+ next unless parent.respond_to?(:key?) && parent.key?(leaf)
16
+
17
+ parent[leaf] = restored(parent[leaf], stored(record, field[:name]), config)
18
+ end
19
+ end
20
+
21
+ def restored(submitted, stored, config)
22
+ structure = submitted.is_a?(String) ? parse(submitted) : plain(submitted)
23
+ return submitted unless structure && JSON.generate(structure).include?(ValuePayload::MASK)
24
+
25
+ result = walk(structure, stored, config)
26
+ submitted.is_a?(String) ? JSON.generate(result) : result
27
+ end
28
+
29
+ def walk(submitted, stored, config)
30
+ case submitted
31
+ when Hash
32
+ submitted.each_with_object({}) do |(key, value), out|
33
+ if value == ValuePayload::MASK && Masking.attribute?(key, config)
34
+ out[key] = stored[key] if stored.is_a?(Hash) && stored.key?(key)
35
+ else
36
+ out[key] = walk(value, stored.is_a?(Hash) ? stored[key] : nil, config)
37
+ end
38
+ end
39
+ when Array then submitted.each_with_index.map { |value, i| walk(value, stored.is_a?(Array) ? stored[i] : nil, config) }
40
+ else submitted
41
+ end
42
+ end
43
+
44
+ def stored(record, name)
45
+ value = record&.try(name)
46
+ value.is_a?(String) ? parse(value) : value.as_json
47
+ end
48
+
49
+ def parse(text)
50
+ JSON.parse(text)
51
+ rescue JSON::ParserError
52
+ nil
53
+ end
54
+
55
+ def plain(value)
56
+ case value
57
+ when ActionController::Parameters then value.to_unsafe_h.to_h
58
+ when Hash, Array then value
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,100 @@
1
+ module ReactiveAdmin
2
+ # Credentials and secrets never go over the API: their values in index cells, show rows and form
3
+ # fields are replaced by a `masked` node. Which attributes count is decided by name, from
4
+ # `config.masked_attributes`, a resource's `reactive { mask :token }` and, unless turned off with
5
+ # `config.mask_filter_parameters = false`, Rails' `filter_parameters`. Only attribute-keyed values
6
+ # are masked: a column or row computed by a block is the host's to handle.
7
+ module Masking
8
+ NODE = {type: "masked"}.freeze
9
+ CLASS_NAME = "reactiveadmin-masked".freeze
10
+ CSV_PLACEHOLDER = "[MASKED]".freeze
11
+
12
+ # Rendered where AA's helpers would print the value; HtmlNodes turns it into NODE.
13
+ def self.html = %(<span class="#{CLASS_NAME}"></span>).html_safe
14
+
15
+ class << self
16
+ def attribute?(name, config = nil)
17
+ name = name.to_s
18
+ return false if name.empty?
19
+
20
+ explicit?(name, config) || (ReactiveAdmin.config.mask_filter_parameters && filtered?(name))
21
+ end
22
+
23
+ # Masked by the host's own declaration, as opposed to inferred from `filter_parameters`.
24
+ def explicit?(name, config = nil) = match?([*ReactiveAdmin.config.masked_attributes, *config&.reactive_options&.[](:mask)], name.to_s)
25
+
26
+ # An empty value shows as empty: masking it would only claim a secret is set.
27
+ def node(config, name, value) = (NODE if value.present? && attribute?(name, config))
28
+
29
+ # Makes AA's `format_attribute` (index cells, attributes_table rows) mask for this view only,
30
+ # so the classic admin is untouched.
31
+ def install(view, config)
32
+ view.instance_variable_set(:@reactiveadmin_mask_config, config)
33
+ view.extend(Display)
34
+ end
35
+
36
+ # A blank value for a masked attribute means "unchanged": the form never receives the current
37
+ # value, so submitting it back blank must not wipe the secret. With a `record`, only its present
38
+ # values are protected; a blank one has nothing to keep, and the blank is written as classic does.
39
+ def keep_unchanged(params, config, record = nil)
40
+ params.keys.each do |key|
41
+ value = params[key]
42
+ if value.respond_to?(:keys) then keep_unchanged(value, config)
43
+ elsif value.is_a?(Array) then value.each { keep_unchanged(it, config) if it.respond_to?(:keys) }
44
+ elsif (value.nil? || value == "") && attribute?(key, config) && !(record && record.try(key).blank?) then params.delete(key)
45
+ end
46
+ end
47
+ end
48
+
49
+ private
50
+
51
+ def match?(list, name) = list.any? { it.is_a?(Regexp) ? it.match?(name) : it.to_s == name }
52
+
53
+ def filtered?(name)
54
+ filters = Rails.application.config.filter_parameters
55
+ (@filters, @parameter_filter = filters.hash, ActiveSupport::ParameterFilter.new(filters)) unless @filters == filters.hash
56
+ @parameter_filter.filter(name => +"x")[name] != "x"
57
+ end
58
+ end
59
+
60
+ module Display
61
+ def format_attribute(resource, attr)
62
+ config = @reactiveadmin_mask_config
63
+ masks = (attr.is_a?(Symbol) || attr.is_a?(String)) && Masking.attribute?(attr, config)
64
+ (masks && AA.find_value(self, resource, attr).present?) ? Masking.html : super
65
+ end
66
+ end
67
+
68
+ # Behind `config.mask_csv` (on by default): AA's own export, classic and API alike.
69
+ module Csv
70
+ # A json column is exported whole, so a secret inside it is masked by its key, as the `_value` endpoint does.
71
+ def self.mask_nested(value, config) = ValuePayload.masked_key?(value, config) ? ValuePayload.mask(value, config) : value
72
+
73
+ def build(controller, csv)
74
+ @reactiveadmin_config = AA.config_of(controller)
75
+ super
76
+ end
77
+
78
+ # An associated record exports as its id: its display name can identify a person.
79
+ def build_row(resource, columns, options)
80
+ mask = ReactiveAdmin.config.mask_csv
81
+ config = @reactiveadmin_config
82
+ columns = columns.map do |column|
83
+ next column unless column.data.is_a?(Symbol)
84
+
85
+ data = column.data
86
+ masked = mask && Masking.attribute?(data, config)
87
+ AA.column_with_data(column, lambda { |record|
88
+ value = record.public_send(data)
89
+ next (CSV_PLACEHOLDER if value.present?) if masked
90
+
91
+ next value.to_param if value.is_a?(ActiveRecord::Base)
92
+
93
+ mask ? Csv.mask_nested(value, config) : value
94
+ })
95
+ end
96
+ super
97
+ end
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,111 @@
1
+ module ReactiveAdmin
2
+ module Mcp
3
+ # How much of a resource or page agents get: `config.mcp.default`, or `reactive { mcp ... }` in its
4
+ # registration. A mode reads as one more `api` guard on MCP requests, so it narrows what the guards
5
+ # leave open and never widens it.
6
+ #
7
+ # :none left out of MCP: not listed, every tool answers as for an unknown resource
8
+ # :read_only reads only; `actions:` adds custom or batch actions agents may run
9
+ # :full everything the api guards and the policy allow
10
+ module Access
11
+ MODES = %i[none read_only full].freeze
12
+ REASONS = {none: "Not available to agents", read_only: "Agents only read this"}.freeze
13
+ # What each resource tool exercises, for the doctor.
14
+ TOOLS = {"list_records" => %w[index], "get_record" => %w[show], "get_form" => %w[new edit],
15
+ "create_record" => %w[create], "update_record" => %w[update], "delete_record" => %w[destroy]}.freeze
16
+
17
+ module_function
18
+
19
+ def declare(config, mode = nil, actions: nil)
20
+ raise ArgumentError, "mcp needs a mode: #{MODES.map(&:inspect).join(", ")}" if mode.nil? && actions.nil?
21
+
22
+ mode = (mode || :read_only).to_sym
23
+ raise ArgumentError, "mcp #{mode.inspect}: expected one of #{MODES.map(&:inspect).join(", ")}" unless MODES.include?(mode)
24
+ raise ArgumentError, "mcp #{mode.inspect} takes no actions: they only add to :read_only" if actions && mode != :read_only
25
+
26
+ config.reactive_options[:mcp] = {mode:, actions: Array(actions).flatten.map(&:to_s)}
27
+ end
28
+
29
+ def mode(config) = config.try(:reactive_options)&.dig(:mcp, :mode) || ReactiveAdmin.config.mcp.default
30
+
31
+ def listed(config) = config.try(:reactive_options)&.dig(:mcp, :actions) || []
32
+
33
+ def visible?(config) = mode(config) != :none
34
+
35
+ # The guard the mode amounts to, nil for :full. A read-only one leaves the listed custom and batch actions out of its reach.
36
+ def declaration(config)
37
+ case mode(config)
38
+ when :none then ApiGuards::Declaration.new(guard: :deny, only: nil, except: nil, attributes: nil, reason: REASONS[:none])
39
+ when :read_only then ApiGuards::Declaration.new(guard: :read_only, only: nil, except: nil, attributes: nil, reason: REASONS[:read_only], exempt: listed(config).presence)
40
+ end
41
+ end
42
+
43
+ # The mode alone, not the api guards: what it refuses answers as unknown, what a guard refuses names the guard.
44
+ def allows?(config, names, verb: nil)
45
+ declaration = declaration(config) or return true
46
+ names = names.map(&:to_s)
47
+ !(ApiGuards.applies?(declaration, names) && ApiGuards.refuses_statically?(declaration, config, names, verb:, channel: :mcp))
48
+ end
49
+
50
+ # Whether the mode lets a call through for at least one of these verbs; with none, as for any verb.
51
+ def allows_any?(config, names, verbs) = verbs.empty? ? allows?(config, names) : verbs.any? { allows?(config, names, verb: it) }
52
+
53
+ def offers?(config, name) = Registry.actions(config).include?(name.to_sym) && allows?(config, [name])
54
+
55
+ # Custom and batch actions the mode lets run_action reach.
56
+ def runnable(config)
57
+ [*AA.custom_actions(config).select { allows_any?(config, [it.name.to_s], verbs_of(it)) }.map { it.name.to_s },
58
+ *AA.batch_actions(config).map { it.sym.to_s }.select { allows?(config, ["batch_action", it]) }].uniq
59
+ end
60
+
61
+ def verbs_of(action) = Array.wrap(action.http_verb).map { it.to_s.upcase }
62
+
63
+ # Whether any resource offers one of these actions, so a tool no resource offers stays out of tools/list.
64
+ def anywhere?(*names) = Registry.resources.any? { |config| names.any? { offers?(config, it) } }
65
+
66
+ def any_runnable? = Registry.resources.any? { runnable(it).any? }
67
+
68
+ def any_visible?(configs) = configs.any? { visible?(it) }
69
+
70
+ # What agents reach of each served resource and page, after the api guards, for the doctor.
71
+ def surface
72
+ [*Registry.resources, *Registry.pages].select { Exposure.allowed?(it) }.map do |config|
73
+ page = AA.page?(config)
74
+ tools, actions = open_to_agents(config, page)
75
+ {key: Exposure.key(config), kind: page ? "page" : "resource", mode: mode(config).to_s, tools:, actions:}
76
+ end
77
+ end
78
+
79
+ def open_to_agents(config, page)
80
+ return [[], []] if ApiGuards.whole?(config, channel: :mcp)
81
+
82
+ open = ->(*names) { !ApiGuards.denial(config, names, channel: :mcp) }
83
+ open_verb = ->(action) { verbs_of(action).any? { !ApiGuards.denial(config, [action.name.to_s], verb: it, channel: :mcp) } }
84
+ actions = page ? [] : [*AA.custom_actions(config).select { open_verb.call(it) }.map { it.name.to_s },
85
+ *AA.batch_actions(config).map { it.sym.to_s }.select { open.call("batch_action", it) }].uniq
86
+ tools = if page
87
+ open.call("index") ? %w[get_page] : []
88
+ else
89
+ TOOLS.select { |_, names| names.any? { Registry.actions(config).include?(it.to_sym) && open.call(it) } }.keys
90
+ end
91
+ tools << "run_action" if actions.any?
92
+ [tools, actions]
93
+ end
94
+
95
+ def sensitive?(config) = !AA.page?(config) && (LookupAudit.sensitive_resource?(config) || masked?(config))
96
+
97
+ def masked?(config) = config.reactive_options[:mask].present? || config.resource_class.column_names.any? { Masking.attribute?(it, config) }
98
+
99
+ # :full on a resource whose names or attributes the host already treats as sensitive.
100
+ def audit
101
+ return [] unless ReactiveAdmin.config.mcp.possibly_enabled?
102
+
103
+ Registry.resources.select { mode(it) == :full && Exposure.allowed?(it) && sensitive?(it) }.map do |config|
104
+ key = Exposure.key(config)
105
+ {kind: :mcp_full_sensitive, resource: key,
106
+ reason: "#{key} is mcp :full but is sensitive or masks attributes: agents may write it; prefer :read_only and list the actions they need"}
107
+ end
108
+ end
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,123 @@
1
+ module ReactiveAdmin
2
+ module Mcp
3
+ # Calls the admin API through the host's whole Rack stack, as the caller: same Authorization header,
4
+ # so its authentication, authorization, masking, audit events and rate limits apply to every tool.
5
+ class Api
6
+ Result = Data.define(:status, :body, :headers) do
7
+ def ok? = status.between?(200, 299)
8
+ end
9
+
10
+ FORWARDED = %w[REMOTE_ADDR HTTP_USER_AGENT HTTP_X_FORWARDED_FOR HTTP_X_FORWARDED_PROTO HTTP_X_REAL_IP].freeze
11
+ # Set by the server only (a client's header arrives as HTTP_*), for hosts that tell MCP traffic apart.
12
+ ENV_KEY = "reactiveadmin.mcp".freeze
13
+
14
+ # Status of the most recent call, for the audit event.
15
+ attr_accessor :last_status
16
+
17
+ def initialize(request) = @request = request
18
+
19
+ def get!(path, query = {}) = call!("GET", path, query:)
20
+
21
+ def call!(verb, path, query: {}, body: nil)
22
+ result = call(verb, path, query:, body:)
23
+ raise error_for(result) unless result.ok?
24
+
25
+ result.body
26
+ end
27
+
28
+ def call(verb, path, query: {}, body: nil)
29
+ status, headers, chunks = isolated { Rails.application.call(env_for(verb, path, query, body)).then { read(it) } }
30
+ self.last_status = status
31
+ Result.new(status:, body: parse(chunks), headers:)
32
+ end
33
+
34
+ private
35
+
36
+ def env_for(verb, path, query, body)
37
+ uri = query.compact_blank.empty? ? path : "#{path}?#{query.compact.to_query}"
38
+ env = Rack::MockRequest.env_for(uri, :method => verb, :input => body&.to_json, "CONTENT_TYPE" => ("application/json" if body), "HTTP_ACCEPT" => "application/json")
39
+ env.merge!(@request.env.slice(*FORWARDED))
40
+ env.merge!("HTTP_HOST" => @request.host_with_port, "SERVER_NAME" => @request.host, "SERVER_PORT" => @request.port.to_s,
41
+ "rack.url_scheme" => @request.scheme, "SCRIPT_NAME" => @request.script_name, "HTTP_X_REQUEST_ID" => @request.request_id, "HTTP_AUTHORIZATION" => @request.authorization, ENV_KEY => true)
42
+ env[Audit::CORRELATION_ENV] = @request.request_id
43
+ env["HTTPS"] = "on" if @request.ssl?
44
+ env.compact
45
+ end
46
+
47
+ def read(response)
48
+ status, headers, body = response
49
+ chunks = +""
50
+ body.each { chunks << it }
51
+ [status, headers, chunks]
52
+ ensure
53
+ body.close if body.respond_to?(:close)
54
+ end
55
+
56
+ def parse(chunks)
57
+ JSON.parse(chunks) if chunks.start_with?("{", "[")
58
+ rescue JSON::ParserError
59
+ nil
60
+ end
61
+
62
+ # Rails' executor middleware starts a fresh execution with `reset: true`, completing the one this
63
+ # request is running in, which would clear the host's CurrentAttributes mid-request. Set the outer
64
+ # execution aside for the nested call and put everything back after.
65
+ def isolated
66
+ state = ActiveSupport::IsolatedExecutionState
67
+ keys = [Rails.application.executor, Rails.application.reloader].filter_map { it.active_key if it.respond_to?(:active_key) }
68
+ outer = keys.index_with { state.delete(it) }.compact
69
+ current = ActiveSupport::CurrentAttributes.descendants.to_h { [it, it.instance.attributes] }
70
+ yield
71
+ ensure
72
+ outer&.each { |key, execution| state[key] = execution }
73
+ current&.each { |klass, attributes| klass.instance.attributes = attributes }
74
+ end
75
+
76
+ def error_for(result)
77
+ body = result.body.is_a?(Hash) ? result.body : {}
78
+ ToolError.new(message_for(result.status, body, result.headers), status: result.status, code: body["code"])
79
+ end
80
+
81
+ def message_for(status, body, headers)
82
+ code = body["code"]
83
+ case status
84
+ when 401 then "Authentication failed: the token was rejected or has expired. Ask the user to re-authorize."
85
+ when 403 then forbidden_message(code, body)
86
+ when 404 then "Not found: #{body["message"]}. The resource, record or action doesn't exist, or the user can't see it."
87
+ when 409 then (code == "retry") ? "Busy: nothing was changed. Retry the same call." : "Stale: the record changed since it was loaded. Call get_form again, review the current values and retry with the new lock."
88
+ when 422 then validation_message(body)
89
+ when 429 then "Rate limited. Retry in #{headers["Retry-After"] || "a few"} seconds."
90
+ when 400 then "Bad request: #{body["message"]}"
91
+ when 501 then body["message"].to_s
92
+ else "The admin API failed (HTTP #{status}#{" #{code}" if code})."
93
+ end
94
+ end
95
+
96
+ def forbidden_message(code, body)
97
+ case code
98
+ when "insufficient_scope" then "#{body["message"]}. Ask the user to grant it."
99
+ when "api_denied" then api_denied_message(body)
100
+ else "Not authorized: the user's account may not do this. Do not retry; tell the user."
101
+ end
102
+ end
103
+
104
+ DENIALS = {"read_only" => "Read-only through the API", "session_only" => "Not available to API tokens"}.freeze
105
+
106
+ # Final, like any refusal: it names the classic page so the user can do it themselves.
107
+ def api_denied_message(body)
108
+ reason = body["message"].to_s.delete_suffix(".") unless ApiGuards::MESSAGES.value?(body["message"])
109
+ attributes = " Reserved: #{body["attributes"].join(", ")}." if body["attributes"].present?
110
+ path = body["classic_url"].to_s
111
+ url = " at #{@request.base_url}#{path}" if path.start_with?("/")
112
+ "#{denial(body["guard"])}#{": #{reason}" if reason.present?}.#{attributes} Do not retry or work around it; tell the user to use the classic admin#{url}."
113
+ end
114
+
115
+ def denial(guard) = DENIALS.fetch(guard.to_s) { ApiGuards::STATIC.include?(guard.to_s.to_sym) ? "Refused by the API" : "Refused by the API guard #{guard}" }
116
+
117
+ def validation_message(body)
118
+ problems = body.fetch("errors", {}).map { |field, messages| "#{field} #{Array(messages).join(", ")}" } + Array(body["base"])
119
+ "Validation failed: #{problems.presence&.join("; ") || body["message"]}"
120
+ end
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,22 @@
1
+ module ReactiveAdmin
2
+ module Mcp
3
+ module Tools
4
+ # Asks the index for one row and reads the page meta, so authorization, scoping, the declared-filter
5
+ # allowlist and the ransack guard are the index's own. The row is dropped: only counts are returned.
6
+ define :count_records, title: "Count records",
7
+ description: "How many records match, without reading them: the total for the filters and scope, and the count per scope. Use it before list_records to size a query, or to answer how-many questions. filters and scope work as in list_records.",
8
+ properties: {resource: RESOURCE, parent_id: PARENT, filters: {type: "object", description: "Declared filter params to values."},
9
+ scope: {type: "string", description: "Scope id from describe_resource."}}, required: [:resource] do |ctx, args|
10
+ filters = args.fetch("filters", {})
11
+ bad = filters.keys.grep_v(FILTER_NAME)
12
+ raise ToolError, "Invalid filter name #{bad.first.to_s.first(40).inspect}." if bad.any?
13
+
14
+ meta = ctx.api.get!(ctx.collection_path(args), {q: filters.presence, scope: args["scope"], per_page: 1})["meta"]
15
+ scopes = meta["scopes"].map { it.slice("id", "name", "count").compact }.presence
16
+ total = meta["total_count"]
17
+ {resource: args["resource"], total:, scope: meta["current_scope"], scopes:,
18
+ note: ("This resource doesn't count totals, so none is available." if total.nil?)}.compact
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,175 @@
1
+ module ReactiveAdmin
2
+ module Mcp
3
+ # Reduces the API's typed nodes to what an agent reads best: plain values for cells and rows, and
4
+ # plain text for layout. Values the server withheld (masked, summarized, truncated) stay that way.
5
+ module Layout
6
+ BLOCKS = %w[group box columns column toolbar blockquote].freeze
7
+
8
+ module_function
9
+
10
+ def value(node)
11
+ return node unless node.is_a?(Hash)
12
+
13
+ case node["type"]
14
+ when "empty" then nil
15
+ when "text", "code" then text(node)
16
+ when "number", "boolean", "date", "datetime" then node["value"]
17
+ when "status" then node["label"]
18
+ when "ref" then ref(node)
19
+ when "link" then link(node)
20
+ when "json" then json(node)
21
+ when "masked" then "[masked]"
22
+ when "error" then "[error: #{node["label"]}]"
23
+ when "image" then "[image: #{node["alt"].presence || "no description"}]"
24
+ when "document" then "[document: #{node["title"].presence || "PDF"}]"
25
+ when "action" then action_text(node)
26
+ when "html", "frame" then plain(node["html"])
27
+ else node["text"] || node["label"] || node["type"]
28
+ end
29
+ end
30
+
31
+ def text(node)
32
+ return node["text"] unless node["truncated"]
33
+
34
+ {text: node["text"], truncated: true, expand_path: node["expand_path"]}.compact
35
+ end
36
+
37
+ def ref(node)
38
+ target = node["ref"]
39
+ {ref: ("#{target["resource"]}/#{target["id"]}" if target), label: node["label"]}.compact
40
+ end
41
+
42
+ def link(node)
43
+ return node["label"] unless node["external"] || node["ref"]
44
+
45
+ node["external"] ? {label: node["label"], url: node["href"]} : ref(node)
46
+ end
47
+
48
+ def json(node)
49
+ return node["value"] if node.key?("value")
50
+
51
+ {summary: node["summary"], expand_path: node["expand_path"]}.compact
52
+ end
53
+
54
+ def plain(html)
55
+ fragment = HtmlPolicy.parse(html) or return ""
56
+ fragment.css("script, style").remove
57
+ fragment.text.squish
58
+ end
59
+
60
+ def action_text(node)
61
+ action = node["action"] || {}
62
+ "[action #{action["key"]}: #{action["label"]}#{" (#{action["method"].to_s.upcase})" if action["method"]}]"
63
+ end
64
+
65
+ # One line for a node and everything inside it.
66
+ def inline(node)
67
+ return node["children"].map { inline(it) }.join.squish if node.is_a?(Hash) && node["children"]
68
+
69
+ value(node).then { it.is_a?(String) ? it : it.to_json }
70
+ end
71
+
72
+ # Layout as markdown-ish text. `rows` skips attribute tables, which `attributes` reads as fields.
73
+ def render(nodes, rows: true)
74
+ Array(nodes).filter_map { block(it, rows) }.join("\n").strip
75
+ end
76
+
77
+ # Fields of the GET forms of a response (a page's layout, or a template's own form and its layout): the
78
+ # ones a read may carry as a query. Fields the API refuses to write are no better to filter by.
79
+ def query_fields(body)
80
+ own = (body["action"]&.dig("method") == "get") ? Array(body.dig("form", "sections")).flat_map { it["fields"] || [] } : []
81
+ (own + get_forms(body["layout"])).reject { it["param"].blank? || it["control"] == "html" }
82
+ end
83
+
84
+ def get_forms(nodes)
85
+ Array(nodes).flat_map do |node|
86
+ next [] unless node.is_a?(Hash)
87
+
88
+ own = (node["type"] == "form" && node.dig("form", "action", "method") == "get") ? node["form"]["form"]["sections"].flat_map { it["fields"] || [] } : []
89
+ own + get_forms(node["children"])
90
+ end
91
+ end
92
+
93
+ # Label => value for every attributes table and definition list in the layout.
94
+ def attributes(nodes)
95
+ Array(nodes).flat_map { |node| collect(node) }.each_with_object({}) do |(label, value), fields|
96
+ label = "#{label} (#{fields.size})" while fields.key?(label)
97
+ fields[label] = value
98
+ end
99
+ end
100
+
101
+ def collect(node)
102
+ return [] unless node.is_a?(Hash)
103
+ return node["rows"].map { |row| [row["label"], row_value(row["value"])] } if %w[attributes_table definition_list].include?(node["type"])
104
+
105
+ Array(node["children"]).flat_map { collect(it) }
106
+ end
107
+
108
+ def row_value(nodes)
109
+ values = Array(nodes).map { value(it) }
110
+ if values.size == 1
111
+ values.first
112
+ else
113
+ values.map { it.is_a?(String) ? it : it.to_json }.join(" ")
114
+ end
115
+ end
116
+
117
+ def actions(nodes)
118
+ Array(nodes).flat_map do |node|
119
+ next [] unless node.is_a?(Hash)
120
+
121
+ found = (node["type"] == "action" && node["action"]) ? [node["action"]] : []
122
+ found + actions(node["header_actions"]) + actions(node["children"])
123
+ end
124
+ end
125
+
126
+ def block(node, rows)
127
+ return unless node.is_a?(Hash)
128
+
129
+ children = -> { render(node["children"], rows:).presence }
130
+ case node["type"]
131
+ when "panel" then titled(node["title"], [children.call, *Array(node["header_actions"]).filter_map { inline(it).presence }].compact.join("\n").presence)
132
+ when "tab" then titled(node["title"], children.call)
133
+ when "tabs", *BLOCKS then children.call
134
+ when "attributes_table", "definition_list" then rows ? table_rows(node) : nil
135
+ when "table" then table(node)
136
+ when "list" then list(node)
137
+ when "heading" then "#{"#" * node.fetch("level", 2).to_i.clamp(1, 6)} #{inline(node)}"
138
+ when "divider" then "---"
139
+ when "disclosure" then [Array(node["summary_nodes"]).map { inline(it) }.join, children.call].compact_blank.join("\n").presence
140
+ when "form" then form_text(node)
141
+ when "iframe", "frame" then "[interactive content omitted: open it in the admin UI]"
142
+ else inline(node).presence
143
+ end
144
+ end
145
+
146
+ # A GET form reads like a query; any other form is for the UI. The response's own form has no payload.
147
+ def form_text(node)
148
+ return unless node["form"]
149
+
150
+ (node.dig("form", "action", "method") == "get") ? "[filter form: its fields are the query_fields]" : "[interactive content omitted: open it in the admin UI]"
151
+ end
152
+
153
+ def titled(title, body) = (if body
154
+ title.present? ? "## #{title}\n#{body}" : body
155
+ end)
156
+
157
+ def table_rows(node)
158
+ lines = node["rows"].map { |row| "- #{row["label"]}: #{row_value(row["value"]).then { it.is_a?(String) ? it : it.to_json }}" }
159
+ [("### #{node["title"]}" if node["title"].present?), *lines].compact.join("\n")
160
+ end
161
+
162
+ def table(node)
163
+ header = node["headers"].join(" | ")
164
+ lines = node["rows"].map { |cells| cells.map { |cell| cell.is_a?(Array) ? cell.map { inline(it) }.join(" ") : inline(cell) }.join(" | ") }
165
+ [header, *lines].join("\n")
166
+ end
167
+
168
+ def list(node)
169
+ node["children"].each_with_index.map do |item, index|
170
+ "#{node["ordered"] ? "#{index + 1}." : "-"} #{Array(item["children"]).map { inline(it) }.join(" ")}"
171
+ end.join("\n")
172
+ end
173
+ end
174
+ end
175
+ end
@@ -0,0 +1,46 @@
1
+ module ReactiveAdmin
2
+ module Mcp
3
+ # Keeps a tool result inside the byte budget, saying so when it cuts something. Long strings are
4
+ # clipped first, then the rows (or text) the caller names are trimmed until the result fits.
5
+ module Output
6
+ STRING_LIMIT = 1_000
7
+ MIN_TEXT = 200
8
+
9
+ module_function
10
+
11
+ def render(payload, limit:, rows: nil, text: nil)
12
+ payload = clip(payload.except(text)).merge(payload.slice(text))
13
+ payload = trim_rows(payload, rows, limit) if rows && size(payload) > limit
14
+ payload = trim_text(payload, text, limit) if text && size(payload) > limit
15
+ json = JSON.generate(payload)
16
+ return json if json.bytesize <= limit
17
+
18
+ "#{json.byteslice(0, limit).scrub("")}\n[truncated at #{limit} bytes: narrow the request]"
19
+ end
20
+
21
+ def size(payload) = JSON.generate(payload).bytesize
22
+
23
+ def clip(value)
24
+ case value
25
+ when String then (value.length > STRING_LIMIT) ? "#{value[0, STRING_LIMIT]}... [#{value.length - STRING_LIMIT} more characters cut]" : value
26
+ when Array then value.map { clip(it) }
27
+ when Hash then value.transform_values { clip(it) }
28
+ else value
29
+ end
30
+ end
31
+
32
+ def trim_rows(payload, key, limit)
33
+ rows = payload[key]
34
+ keep = rows.size
35
+ keep -= 1 while keep.positive? && size(payload.merge(key => rows.first(keep))) > limit - 300
36
+ payload.merge(key => rows.first(keep), :truncated => "Showing #{keep} of #{rows.size} #{key} because the response limit was reached. Request a smaller per_page, add filters, or fetch a single record.")
37
+ end
38
+
39
+ def trim_text(payload, key, limit)
40
+ text = payload[key].to_s
41
+ room = [limit - size(payload.merge(key => "")) - 300, MIN_TEXT].max
42
+ payload.merge(key => text.byteslice(0, room).scrub(""), :truncated => "#{key} cut at #{room} bytes of #{text.bytesize}; read single pages or fields for the rest.")
43
+ end
44
+ end
45
+ end
46
+ end