maquina-generators 0.9.0 → 0.11.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 (169) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +201 -12
  3. data/lib/generators/maquina/app/USAGE +4 -0
  4. data/lib/generators/maquina/app/app_generator.rb +38 -7
  5. data/lib/generators/maquina/app/templates/README.md.erb +21 -0
  6. data/lib/generators/maquina/app/templates/app/views/home/index.html.erb +1 -1
  7. data/lib/generators/maquina/auth_flavor.rb +59 -0
  8. data/lib/generators/maquina/backstage_signin/backstage_signin.rb +320 -0
  9. data/lib/generators/maquina/backstage_signin/templates/test/integration/backstage_access_test.rb.tt +104 -0
  10. data/lib/generators/maquina/csp_reports/csp_reports_generator.rb +13 -1
  11. data/lib/generators/maquina/csp_reports/templates/app/models/mcp/tools/csp_reports.rb +71 -0
  12. data/lib/generators/maquina/csp_reports/templates/test/models/mcp/tools/csp_reports_test.rb +35 -0
  13. data/lib/generators/maquina/error_context/USAGE +22 -0
  14. data/lib/generators/maquina/error_context/error_context_generator.rb +51 -0
  15. data/lib/generators/maquina/mcp/USAGE +38 -0
  16. data/lib/generators/maquina/mcp/mcp_generator.rb +194 -0
  17. data/lib/generators/maquina/mcp/mcp_sibling_tools.rb +122 -0
  18. data/lib/generators/maquina/mcp/templates/app/controllers/concerns/mcp_authenticatable.rb +63 -0
  19. data/lib/generators/maquina/mcp/templates/app/controllers/mcp_controller.rb +205 -0
  20. data/lib/generators/maquina/mcp/templates/app/models/mcp/tool_definitions.rb +38 -0
  21. data/lib/generators/maquina/mcp/templates/app/models/mcp/tool_error.rb +17 -0
  22. data/lib/generators/maquina/mcp/templates/app/models/mcp/tools/app.rb +51 -0
  23. data/lib/generators/maquina/mcp/templates/app/models/mcp/tools.rb +83 -0
  24. data/lib/generators/maquina/mcp/templates/app/models/mcp/user_scope.rb +50 -0
  25. data/lib/generators/maquina/mcp/templates/config/initializers/mcp_cors.rb +38 -0
  26. data/lib/generators/maquina/mcp/templates/test/integration/mcp_conformance_test.rb +223 -0
  27. data/lib/generators/maquina/mcp/templates/test/integration/mcp_flow_test.rb.tt +65 -0
  28. data/lib/generators/maquina/mcp/templates/test/models/mcp/tools_test.rb.tt +145 -0
  29. data/lib/generators/maquina/mcp/templates/test/test_helpers/mcp_test_helper.rb.tt +103 -0
  30. data/lib/generators/maquina/mcp_tool/USAGE +26 -0
  31. data/lib/generators/maquina/mcp_tool/mcp_tool_generator.rb +239 -0
  32. data/lib/generators/maquina/mcp_tool/templates/test/models/mcp/tools/tool_test.rb.tt +49 -0
  33. data/lib/generators/maquina/mission_control_jobs/USAGE +5 -0
  34. data/lib/generators/maquina/mission_control_jobs/mission_control_jobs_generator.rb +21 -5
  35. data/lib/generators/maquina/mission_control_jobs/templates/app/views/backstage_dashboard/index.html.erb.tt +1 -1
  36. data/lib/generators/maquina/mission_control_jobs/templates/app/views/layouts/_admin_navigation.html.erb.tt +12 -11
  37. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/_filters.html.erb +1 -1
  38. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/_general_information.html.erb +1 -1
  39. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/_job.html.erb +1 -1
  40. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/failed/_job.html.erb +1 -1
  41. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/queues/_job.html.erb +1 -1
  42. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/shared/_job.html.erb +1 -1
  43. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/workers/_worker.html.erb +1 -1
  44. data/lib/generators/maquina/oauth/USAGE +35 -0
  45. data/lib/generators/maquina/oauth/oauth_generator.rb +359 -0
  46. data/lib/generators/maquina/oauth/templates/app/controllers/connected_applications_controller.rb +26 -0
  47. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/authorization_servers_controller.rb +24 -0
  48. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/authorizations_controller.rb +92 -0
  49. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/protected_resources_controller.rb +14 -0
  50. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/revocations_controller.rb +20 -0
  51. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/tokens_controller.rb +67 -0
  52. data/lib/generators/maquina/oauth/templates/app/models/access_token.rb +83 -0
  53. data/lib/generators/maquina/oauth/templates/app/models/connected_application.rb +49 -0
  54. data/lib/generators/maquina/oauth/templates/app/models/mcp.rb.tt +33 -0
  55. data/lib/generators/maquina/oauth/templates/app/models/oauth_authorization_code.rb +52 -0
  56. data/lib/generators/maquina/oauth/templates/app/models/oauth_client/metadata_fetcher.rb +195 -0
  57. data/lib/generators/maquina/oauth/templates/app/models/oauth_client.rb +50 -0
  58. data/lib/generators/maquina/oauth/templates/app/views/connected_applications/index.html.erb +43 -0
  59. data/lib/generators/maquina/oauth/templates/app/views/oauth/authorizations/error.html.erb +8 -0
  60. data/lib/generators/maquina/oauth/templates/app/views/oauth/authorizations/new.html.erb +36 -0
  61. data/lib/generators/maquina/oauth/templates/config/locales/oauth.en.yml +34 -0
  62. data/lib/generators/maquina/oauth/templates/config/locales/oauth.es.yml +34 -0
  63. data/lib/generators/maquina/oauth/templates/migration_create_access_tokens.rb.tt +20 -0
  64. data/lib/generators/maquina/oauth/templates/migration_create_oauth_authorization_codes.rb.tt +19 -0
  65. data/lib/generators/maquina/oauth/templates/migration_create_oauth_clients.rb.tt +14 -0
  66. data/lib/generators/maquina/oauth/templates/test/fixtures/access_tokens.yml +48 -0
  67. data/lib/generators/maquina/oauth/templates/test/fixtures/oauth_authorization_codes.yml +11 -0
  68. data/lib/generators/maquina/oauth/templates/test/fixtures/oauth_clients.yml +7 -0
  69. data/lib/generators/maquina/oauth/templates/test/integration/connected_applications_test.rb.tt +70 -0
  70. data/lib/generators/maquina/oauth/templates/test/integration/oauth_authorization_test.rb.tt +150 -0
  71. data/lib/generators/maquina/oauth/templates/test/integration/oauth_discovery_test.rb +44 -0
  72. data/lib/generators/maquina/oauth/templates/test/integration/oauth_tokens_test.rb +147 -0
  73. data/lib/generators/maquina/oauth/templates/test/models/access_token_test.rb.tt +80 -0
  74. data/lib/generators/maquina/oauth/templates/test/models/connected_application_test.rb +41 -0
  75. data/lib/generators/maquina/oauth/templates/test/models/oauth_authorization_code_test.rb +58 -0
  76. data/lib/generators/maquina/oauth/templates/test/test_helpers/oauth_test_helper.rb.tt +82 -0
  77. data/lib/generators/maquina/passkeys/USAGE +4 -2
  78. data/lib/generators/maquina/passkeys/passkeys_generator.rb +16 -11
  79. data/lib/generators/maquina/passkeys/templates/app/controllers/session/{passkeys_controller.rb → passkeys_controller.rb.tt} +6 -2
  80. data/lib/generators/maquina/passkeys/templates/config/locales/{passkeys.en.yml → passkeys.en.yml.tt} +15 -0
  81. data/lib/generators/maquina/passkeys/templates/config/locales/{passkeys.es.yml → passkeys.es.yml.tt} +15 -0
  82. data/lib/generators/maquina/passkeys/templates/test/integration/{passkeys_test.rb → passkeys_test.rb.tt} +6 -0
  83. data/lib/generators/maquina/rack_attack/rack_attack_generator.rb +4 -1
  84. data/lib/generators/maquina/rack_attack/templates/config/initializers/rack_attack.rb.tt +317 -4
  85. data/lib/generators/maquina/registration/registration_generator.rb +32 -0
  86. data/lib/generators/maquina/registration/templates/app/views/registrations/new.html.erb.tt +4 -0
  87. data/lib/generators/maquina/registration/templates/app/views/sessions/new.html.erb.tt +5 -0
  88. data/lib/generators/maquina/security/USAGE +12 -0
  89. data/lib/generators/maquina/security/security_generator.rb +79 -7
  90. data/lib/generators/maquina/security/templates/app/models/mcp/tools/security.rb.tt +114 -0
  91. data/lib/generators/maquina/security/templates/app/views/backstage_dashboard/index.html.erb.tt +1 -1
  92. data/lib/generators/maquina/security/templates/app/views/layouts/_admin_navigation.html.erb.tt +12 -11
  93. data/lib/generators/maquina/security/templates/test/models/mcp/tools/security_test.rb +99 -0
  94. data/lib/generators/maquina/solid_errors/USAGE +21 -10
  95. data/lib/generators/maquina/solid_errors/error_context_files.rb +82 -0
  96. data/lib/generators/maquina/solid_errors/solid_errors_generator.rb +52 -31
  97. data/lib/generators/maquina/solid_errors/templates/app/agents/errors_query.rb +86 -29
  98. data/lib/generators/maquina/solid_errors/templates/app/agents/failure_triage.rb +4 -2
  99. data/lib/generators/maquina/solid_errors/templates/app/agents/list_failures_tool.rb +9 -4
  100. data/lib/generators/maquina/solid_errors/templates/app/models/mcp/tools/solid_errors.rb.tt +132 -0
  101. data/lib/generators/maquina/solid_errors/templates/app/views/backstage_dashboard/index.html.erb.tt +1 -1
  102. data/lib/generators/maquina/solid_errors/templates/app/views/layouts/_admin_navigation.html.erb.tt +12 -11
  103. data/lib/generators/maquina/solid_errors/templates/app/views/solid_errors/errors/show/_actions.html.erb +0 -15
  104. data/lib/generators/maquina/solid_errors/templates/app/views/solid_errors/errors/show/_error_details.html.erb +5 -5
  105. data/lib/generators/maquina/solid_errors/templates/app/views/solid_errors/occurrences/_collection.html.erb +1 -1
  106. data/lib/generators/maquina/solid_errors/templates/config/initializers/error_context.rb +33 -0
  107. data/lib/generators/maquina/solid_errors/templates/test/models/mcp/tools/solid_errors_filters_test.rb +68 -0
  108. data/lib/generators/maquina/solid_errors/templates/test/models/mcp/tools/solid_errors_test.rb +109 -0
  109. data/lib/generators/maquina/solid_queue/USAGE +11 -0
  110. data/lib/generators/maquina/solid_queue/solid_queue_generator.rb +25 -1
  111. data/lib/generators/maquina/solid_queue/templates/app/models/mcp/tools/solid_queue.rb.tt +163 -0
  112. data/lib/generators/maquina/solid_queue/templates/test/models/mcp/tools/solid_queue_test.rb +99 -0
  113. data/lib/maquina_generators/version.rb +1 -1
  114. data/test/fixtures/error_context/0.10.0/app/agents/errors_query.rb +105 -0
  115. data/test/fixtures/error_context/0.10.0/app/agents/failure_triage.rb +21 -0
  116. data/test/fixtures/error_context/0.10.0/app/agents/list_failures_tool.rb +20 -0
  117. data/test/fixtures/error_context/0.10.0/app/models/mcp/tools/solid_errors.rb +81 -0
  118. data/test/fixtures/error_context/0.10.0/app/models/mcp/tools/solid_errors_write.rb +101 -0
  119. data/test/generators/maquina/app_generator_test.rb +67 -5
  120. data/test/generators/maquina/backstage_signin_test.rb +296 -0
  121. data/test/generators/maquina/csp_reports_generator_test.rb +125 -6
  122. data/test/generators/maquina/error_context_generator_test.rb +188 -0
  123. data/test/generators/maquina/mcp_generator_test.rb +429 -0
  124. data/test/generators/maquina/mcp_tool_generator_test.rb +235 -0
  125. data/test/generators/maquina/mission_control_jobs_generator_test.rb +23 -0
  126. data/test/generators/maquina/oauth_client_metadata_fetcher_test.rb +290 -0
  127. data/test/generators/maquina/oauth_generator_test.rb +568 -0
  128. data/test/generators/maquina/passkeys_generator_test.rb +62 -2
  129. data/test/generators/maquina/rack_attack_generator_test.rb +71 -0
  130. data/test/generators/maquina/rack_attack_rules_test.rb +304 -0
  131. data/test/generators/maquina/registration_generator_test.rb +62 -0
  132. data/test/generators/maquina/security_generator_test.rb +188 -13
  133. data/test/generators/maquina/solid_errors_generator_test.rb +299 -33
  134. data/test/generators/maquina/solid_queue_generator_test.rb +175 -25
  135. data/test/support/rails_auth_app.rb +48 -0
  136. data/test/test_helper.rb +1 -0
  137. metadata +90 -41
  138. data/lib/generators/maquina/solid_errors/templates/app/controllers/failures_mcp_controller.rb.tt +0 -65
  139. data/test/tmp/Gemfile +0 -2
  140. data/test/tmp/app/controllers/application_controller.rb +0 -3
  141. data/test/tmp/app/controllers/concerns/authentication.rb +0 -63
  142. data/test/tmp/app/controllers/registration/verification_resends_controller.rb +0 -38
  143. data/test/tmp/app/controllers/registration/verifications_controller.rb +0 -64
  144. data/test/tmp/app/controllers/registrations_controller.rb +0 -63
  145. data/test/tmp/app/controllers/session/verification_resends_controller.rb +0 -44
  146. data/test/tmp/app/controllers/session/verifications_controller.rb +0 -64
  147. data/test/tmp/app/controllers/sessions_controller.rb +0 -56
  148. data/test/tmp/app/helpers/authentication_helper.rb +0 -20
  149. data/test/tmp/app/jobs/authentication_cleanup_job.rb +0 -13
  150. data/test/tmp/app/mailers/verification_mailer.rb +0 -15
  151. data/test/tmp/app/models/account.rb +0 -5
  152. data/test/tmp/app/models/current.rb +0 -5
  153. data/test/tmp/app/models/email_verification.rb +0 -58
  154. data/test/tmp/app/models/session.rb +0 -18
  155. data/test/tmp/app/models/user.rb +0 -37
  156. data/test/tmp/app/views/registration/verifications/new.html.erb +0 -43
  157. data/test/tmp/app/views/registrations/new.html.erb +0 -39
  158. data/test/tmp/app/views/session/verifications/new.html.erb +0 -43
  159. data/test/tmp/app/views/sessions/new.html.erb +0 -40
  160. data/test/tmp/app/views/verification_mailer/verification_code.html.erb +0 -37
  161. data/test/tmp/app/views/verification_mailer/verification_code.text.erb +0 -11
  162. data/test/tmp/config/locales/clave.en.yml +0 -102
  163. data/test/tmp/config/locales/clave.es.yml +0 -102
  164. data/test/tmp/config/routes.rb +0 -12
  165. data/test/tmp/db/migrate/20261019191386_create_accounts.rb +0 -9
  166. data/test/tmp/db/migrate/20261019191387_create_users.rb +0 -17
  167. data/test/tmp/db/migrate/20261019191388_create_sessions.rb +0 -12
  168. data/test/tmp/db/migrate/20261019191389_create_email_verifications.rb +0 -17
  169. data/test/tmp/test/test_helpers/session_test_helper.rb +0 -19
@@ -0,0 +1,38 @@
1
+ Description:
2
+ Adds an MCP server at POST /mcp for protocol revision 2026-07-28, for
3
+ clients signed in through maquina:oauth. Needs maquina:oauth. Hand-rolled:
4
+ no mcp gem and no CORS gem in the app.
5
+
6
+ Stateless JSON-RPC: every request carries its protocol version in
7
+ params._meta and mirrors it, the method and the tool name in the
8
+ MCP-Protocol-Version, Mcp-Method and Mcp-Name headers. server/discover
9
+ answers without a token; tools/list and tools/call need a bearer token
10
+ issued for this server's /mcp. initialize gets a 404 naming 2026-07-28,
11
+ GET and DELETE get a 405. Tools that change data need the write scope
12
+ (403 insufficient_scope otherwise). Calls are rate limited per token.
13
+
14
+ Installs McpController, the McpAuthenticatable concern, a CORS middleware
15
+ (config/initializers/mcp_cors.rb), the tool registry in app/models/mcp/
16
+ (Tools, ToolDefinitions, ToolError, UserScope) and app/models/mcp/tools/app.rb
17
+ with a whoami tool, written only if missing. Tools reach the token's own
18
+ user's data through Mcp::UserScope. If solid_errors, solid_queue, security
19
+ or csp_reports are already installed, their admin-only MCP tools are added
20
+ too. Admin-only tools are for User#backstage_access? (added to
21
+ app/models/user.rb): with Clave, users on the backstage list (backstage.emails
22
+ in credentials); with Rails' sign-in, admins of an account whose
23
+ allow_backstage is on (off by default, so signing up is not enough). Generates a test helper (mcp_post, oauth_token_for), an end-to-end
24
+ flow test, a protocol conformance test and a registry test. Anything it
25
+ cannot place safely is listed after the install.
26
+
27
+ Options:
28
+ --flag NAME Gate MCP behind a feature flag: rewrites Mcp::FLAG = nil in
29
+ app/models/mcp.rb and adds flag-off tests
30
+ --prefix PATH Where maquina:oauth put Connected apps (default /settings)
31
+ --skip-views maquina:oauth ran with --skip-views; the flow test skips its pages
32
+ --quiet Suppress post-install instructions
33
+
34
+ Examples:
35
+ rails g maquina:oauth && rails g maquina:mcp
36
+ rails g maquina:mcp --flag beta_mcp
37
+
38
+ Then: npx @modelcontextprotocol/inspector, connect to http://localhost:3000/mcp
@@ -0,0 +1,194 @@
1
+ require "rails/generators"
2
+ require_relative "mcp_sibling_tools"
3
+ require_relative "../backstage_signin/backstage_signin"
4
+
5
+ module Maquina
6
+ module Generators
7
+ class McpGenerator < Rails::Generators::Base
8
+ include McpSiblingTools
9
+ include BackstageSignin
10
+
11
+ source_root File.expand_path("templates", __dir__)
12
+
13
+ TEST_HELP = /^require "rails\/test_help"\n/
14
+ FLAG_NIL = /^ FLAG = nil$/
15
+ FLAG_NAME = /\A[a-z][a-z0-9_]*\z/
16
+ ROUTES_MARKER = "# MCP (generated by maquina:mcp)"
17
+
18
+ class_option :flag, type: :string, default: nil,
19
+ desc: "Feature flag that gates MCP (rewrites Mcp::FLAG = nil in app/models/mcp.rb)"
20
+ class_option :prefix, type: :string, default: "/settings",
21
+ desc: "Where maquina:oauth put the Connected apps page (for the post-install message)"
22
+ class_option :skip_views, type: :boolean, default: false,
23
+ desc: "maquina:oauth was run with --skip-views: the flow test skips the consent and Connected apps pages"
24
+ class_option :quiet, type: :boolean, default: false,
25
+ desc: "Suppress post-install instructions"
26
+
27
+ # 1. The server authenticates with maquina:oauth's tokens.
28
+ def require_oauth
29
+ unless File.exist?(File.join(destination_root, "app/models/access_token.rb"))
30
+ raise Thor::Error, "maquina:mcp serves tools to clients signed in through maquina:oauth. Run `rails g maquina:oauth` first."
31
+ end
32
+ return if options[:flag].nil? || options[:flag].match?(FLAG_NAME)
33
+
34
+ raise Thor::Error, "--flag must be a lowercase name such as beta_mcp, got #{options[:flag].inspect}."
35
+ end
36
+
37
+ # 2. The endpoint and its bearer authentication
38
+ def create_controllers
39
+ copy_file "app/controllers/mcp_controller.rb", "app/controllers/mcp_controller.rb"
40
+ copy_file "app/controllers/concerns/mcp_authenticatable.rb", "app/controllers/concerns/mcp_authenticatable.rb"
41
+ end
42
+
43
+ # 3. Routes
44
+ def add_routes
45
+ path = File.join(destination_root, "config/routes.rb")
46
+ return @routes_pending = true unless File.exist?(path)
47
+ return if File.read(path).include?(ROUTES_MARKER)
48
+
49
+ route mcp_routes
50
+ end
51
+
52
+ # 4. CORS for browser-based clients
53
+ def create_cors_initializer
54
+ copy_file "config/initializers/mcp_cors.rb", "config/initializers/mcp_cors.rb"
55
+ end
56
+
57
+ # 5. The tool registry. tools/app.rb belongs to the app (and to
58
+ # maquina:mcp_tool) once written, so it is never overwritten.
59
+ def create_registry
60
+ %w[tools tool_definitions tool_error user_scope].each do |name|
61
+ copy_file "app/models/mcp/#{name}.rb", "app/models/mcp/#{name}.rb"
62
+ end
63
+ return if File.exist?(File.join(destination_root, "app/models/mcp/tools/app.rb"))
64
+
65
+ copy_file "app/models/mcp/tools/app.rb", "app/models/mcp/tools/app.rb"
66
+ end
67
+
68
+ # 5b. Who sees the admin-only tools: User#backstage_access?, the same
69
+ # gate that opens the backstage (BackstageSignin).
70
+ def add_backstage_access
71
+ add_backstage_access_to_user
72
+ end
73
+
74
+ # 6. Tools from generators that ran before MCP existed
75
+ def install_sibling_tools
76
+ @sibling_tools = backfill_sibling_mcp_tools
77
+ end
78
+
79
+ # 7. Feature flag: maquina:oauth wrote Mcp::FLAG; point it at --flag.
80
+ def configure_flag
81
+ return unless options[:flag]
82
+
83
+ path = "app/models/mcp.rb"
84
+ full_path = File.join(destination_root, path)
85
+ content = File.exist?(full_path) ? File.read(full_path) : ""
86
+ return if content.include?(flag_line)
87
+ return @flag_pending = true unless content.match?(FLAG_NIL)
88
+
89
+ gsub_file path, FLAG_NIL, flag_line
90
+ end
91
+
92
+ # 8. Test helper and the generated tests
93
+ def create_tests
94
+ template "test/test_helpers/mcp_test_helper.rb.tt", "test/test_helpers/mcp_test_helper.rb"
95
+ template "test/integration/mcp_flow_test.rb.tt", "test/integration/mcp_flow_test.rb"
96
+ copy_file "test/integration/mcp_conformance_test.rb", "test/integration/mcp_conformance_test.rb"
97
+ template "test/models/mcp/tools_test.rb.tt", "test/models/mcp/tools_test.rb"
98
+
99
+ path = File.join(destination_root, "test/test_helper.rb")
100
+ return unless File.exist?(path)
101
+
102
+ content = File.read(path)
103
+ return if content.include?(test_helper_require)
104
+ return @test_helper_pending = true unless content.match?(TEST_HELP)
105
+
106
+ inject_into_file "test/test_helper.rb", "#{test_helper_require}\n", after: TEST_HELP
107
+ end
108
+
109
+ # 9. Post-install message
110
+ def show_post_install
111
+ return if options[:quiet]
112
+
113
+ say ""
114
+ say "The MCP server has been installed!", :green
115
+ say ""
116
+ say "Next steps:", :yellow
117
+ say " 1. bin/rails db:migrate (if maquina:oauth's migrations have not run yet)"
118
+ say " 2. bin/rails test test/integration/mcp_flow_test.rb test/integration/mcp_conformance_test.rb test/models/mcp"
119
+ say " 3. Connect a client: bin/dev, then"
120
+ say " npx @modelcontextprotocol/inspector"
121
+ say " and connect to http://localhost:3000/mcp (Streamable HTTP). Sign in, allow, call whoami."
122
+ say " 4. People see and revoke their connected apps at #{connected_apps_path}"
123
+ say " 5. Add tools: rails g maquina:mcp_tool list_posts status:enum[draft,published]? limit:integer?"
124
+ say ""
125
+ if @sibling_tools.present?
126
+ say "Installed MCP tools for: #{@sibling_tools.join(", ")} (admin only)", :yellow
127
+ say ""
128
+ end
129
+ if rails_auth?
130
+ say "Admin-only tools are for admins of an account with the backstage on (User#backstage_access?):", :yellow
131
+ say " bin/rails db:migrate adds accounts.allow_backstage (off). Turn it on for your account:"
132
+ say " Account.find_by!(name: \"...\").update!(allow_backstage: true)"
133
+ else
134
+ say "Admin-only tools are for people on the backstage list (User#backstage_access?):", :yellow
135
+ say " backstage:"
136
+ say " emails:"
137
+ say " - you@example.com"
138
+ say " in bin/rails credentials:edit. An account's admin role is not enough."
139
+ end
140
+ say ""
141
+ if backstage_signin_pending.any?
142
+ say "Add User#backstage_access? (and, with Clave, User.backstage_emails) to app/models/user.rb by hand:", :yellow
143
+ say backstage_access_methods
144
+ end
145
+ if options[:flag]
146
+ say "MCP is behind the #{options[:flag]} flag (Mcp.enabled_for? in app/models/mcp.rb). Turn it on with", :yellow
147
+ say " features: { #{options[:flag]}: true } in credentials, or #{options[:flag].upcase}=true"
148
+ say ""
149
+ end
150
+ if @routes_pending
151
+ say "Add to config/routes.rb:", :yellow
152
+ say mcp_routes.gsub(/^/, " ")
153
+ say ""
154
+ end
155
+ if @flag_pending
156
+ say "Point the MCP gate at your flag in app/models/mcp.rb:", :yellow
157
+ say " #{flag_line.strip}"
158
+ say ""
159
+ end
160
+ if @test_helper_pending
161
+ say "Load the MCP test helper in test/test_helper.rb:", :yellow
162
+ say " #{test_helper_require}"
163
+ say ""
164
+ end
165
+ say "Optional:", :yellow
166
+ say " - Behind a TLS-terminating proxy, set config.assume_ssl so advertised URLs say https"
167
+ say " - Rate limit: 120 calls a minute per token (McpController); it needs a real cache store"
168
+ say ""
169
+ end
170
+
171
+ private
172
+
173
+ def mcp_routes
174
+ <<~RUBY
175
+ #{ROUTES_MARKER}
176
+ post "mcp", to: "mcp#create", as: :mcp
177
+ match "mcp", to: "mcp#method_not_allowed", via: [:get, :delete]
178
+ RUBY
179
+ end
180
+
181
+ def flag_line
182
+ " FLAG = :#{options[:flag]}"
183
+ end
184
+
185
+ def connected_apps_path
186
+ "#{options[:prefix].to_s.chomp("/")}/connected_apps"
187
+ end
188
+
189
+ def test_helper_require
190
+ %(require_relative "test_helpers/mcp_test_helper")
191
+ end
192
+ end
193
+ end
194
+ end
@@ -0,0 +1,122 @@
1
+ require "erb"
2
+
3
+ module Maquina
4
+ module Generators
5
+ # The MCP tool files the operational generators ship, shared by both sides
6
+ # of the install-order contract: each sibling generator (solid_errors,
7
+ # solid_queue, security, csp_reports) installs its own file when
8
+ # app/models/mcp/tools.rb exists, and maquina:mcp installs the file of every
9
+ # sibling whose marker it finds. Either order ends in the same files.
10
+ #
11
+ # Every method is private: a public method on a generator is a Thor step.
12
+ module McpSiblingTools
13
+ SIBLINGS = %i[solid_errors solid_queue security csp_reports].freeze
14
+ GENERATORS_ROOT = File.expand_path("..", __dir__)
15
+
16
+ # Files a sibling's tools call into, as [owning generator, path].
17
+ SUPPORT_FILES = {
18
+ solid_errors: %w[error_redactor errors_query failure_triage].map { |name| [:solid_errors, "app/agents/#{name}.rb"] },
19
+ solid_queue: [[:solid_errors, "app/agents/error_redactor.rb"]],
20
+ security: [],
21
+ csp_reports: []
22
+ }.freeze
23
+
24
+ private
25
+
26
+ def mcp_installed?
27
+ File.exist?(File.join(destination_root, "app/models/mcp/tools.rb"))
28
+ end
29
+
30
+ # Installs app/models/mcp/tools/<sibling>.rb, its host-app test and the
31
+ # files the tools call. Existing files are kept as they are. Returns true
32
+ # when anything was written.
33
+ def install_mcp_tools(sibling, write: false)
34
+ sibling = sibling.to_sym
35
+ raise ArgumentError, "unknown MCP sibling #{sibling.inspect}" unless SIBLINGS.include?(sibling)
36
+ return false unless mcp_installed?
37
+
38
+ files = SUPPORT_FILES.fetch(sibling) + [
39
+ [sibling, "app/models/mcp/tools/#{sibling}.rb"],
40
+ [sibling, "test/models/mcp/tools/#{sibling}_test.rb"]
41
+ ]
42
+
43
+ written = files.map { |owner, path| install_mcp_sibling_file(owner, path, write: write) }
44
+ (written + install_mcp_feature_tests(sibling)).any?
45
+ end
46
+
47
+ # Host-app tests for a feature a sibling's tool file gained after it
48
+ # first shipped, as [test path, text the tool file has once it has the
49
+ # feature]. An app whose tool file predates the feature gets no test that
50
+ # would fail against it.
51
+ FEATURE_TESTS = {
52
+ solid_errors: [["test/models/mcp/tools/solid_errors_filters_test.rb", "def self.list_failures(scope:, limit: 20, user_id: nil"]]
53
+ }.freeze
54
+
55
+ def install_mcp_feature_tests(sibling)
56
+ tool = File.join(destination_root, "app/models/mcp/tools/#{sibling}.rb")
57
+ return [] unless File.exist?(tool)
58
+
59
+ FEATURE_TESTS.fetch(sibling.to_sym, []).map do |path, marker|
60
+ File.read(tool).include?(marker) && install_mcp_sibling_file(sibling, path, write: false)
61
+ end
62
+ end
63
+
64
+ # The write tools each sibling's --mcp-write adds.
65
+ WRITE_TOOLS = {
66
+ solid_errors: %w[resolve_failure],
67
+ solid_queue: %w[retry_failed_job discard_failed_job],
68
+ security: %w[unban_address],
69
+ csp_reports: []
70
+ }.freeze
71
+
72
+ # --mcp-write was asked for, but the sibling's tool file was already
73
+ # there without every write tool, so install_mcp_tools kept it as it was.
74
+ def mcp_write_pending?(sibling)
75
+ path = File.join(destination_root, "app/models/mcp/tools/#{sibling}.rb")
76
+ return false unless options[:mcp_write] && File.exist?(path)
77
+
78
+ content = File.read(path)
79
+ WRITE_TOOLS.fetch(sibling.to_sym).any? { |tool| !content.include?("def self.#{tool}") }
80
+ end
81
+
82
+ # The read-only variant of every sibling whose marker is present. Returns
83
+ # the siblings that got files.
84
+ def backfill_sibling_mcp_tools
85
+ SIBLINGS.select { |sibling| mcp_sibling_marker?(sibling) && install_mcp_tools(sibling) }
86
+ end
87
+
88
+ def mcp_sibling_marker?(sibling)
89
+ case sibling
90
+ when :solid_errors then mcp_host_file?("config/initializers/solid_errors.rb")
91
+ when :solid_queue then mcp_host_file?("config/solid_queue.yml") || mcp_host_file?("config/queue.yml")
92
+ when :security then mcp_host_file?("app/models/security/abuse_event.rb")
93
+ when :csp_reports
94
+ mcp_host_file?("db/security_schema.rb") &&
95
+ File.read(File.join(destination_root, "db/security_schema.rb")).include?(%("csp_violations"))
96
+ end
97
+ end
98
+
99
+ def mcp_host_file?(path)
100
+ File.exist?(File.join(destination_root, path))
101
+ end
102
+
103
+ # Thor's copy_file and template look the source up through source_paths,
104
+ # which only holds the running generator's templates, so the source is
105
+ # read by absolute path and written with create_file. A `.tt` source is
106
+ # ERB with `write` as its only local.
107
+ def install_mcp_sibling_file(owner, path, write:)
108
+ return false if mcp_host_file?(path)
109
+
110
+ source = File.join(GENERATORS_ROOT, owner.to_s, "templates", path)
111
+ content = if File.exist?("#{source}.tt")
112
+ ERB.new(File.read("#{source}.tt"), trim_mode: "-").result_with_hash(write: write)
113
+ else
114
+ File.read(source)
115
+ end
116
+
117
+ create_file path, content
118
+ true
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,63 @@
1
+ # Bearer-token authentication for the MCP endpoint (generated by maquina:mcp).
2
+ # The token comes from maquina:oauth and must have been issued for this
3
+ # server's /mcp resource (RFC 8707); a token for another resource, a revoked
4
+ # or expired one, or one whose user is blocked all get the same 401.
5
+ #
6
+ # It sets @access_token and @mcp_user. It never touches Current: a token is
7
+ # not a cookie session, so Current.user stays nil under it.
8
+ module McpAuthenticatable
9
+ extend ActiveSupport::Concern
10
+
11
+ # last_used_at feeds the Connected apps page; once a minute is precise
12
+ # enough and spares a write on every call.
13
+ LAST_USED_PRECISION = 1.minute
14
+
15
+ private
16
+
17
+ def authenticate_mcp_token
18
+ token = AccessToken.authenticate(bearer_token)
19
+ unless token && token.resource == mcp_resource
20
+ Rails.logger.info("[MCP] bearer token refused from #{request.remote_ip}")
21
+ return false
22
+ end
23
+
24
+ @access_token = token
25
+ @mcp_user = token.user
26
+ touch_last_used(token)
27
+ true
28
+ end
29
+
30
+ # The raw token, read once and never logged.
31
+ def bearer_token
32
+ request.authorization.to_s[/\ABearer +(\S+)\z/i, 1]
33
+ end
34
+
35
+ def touch_last_used(token)
36
+ return if token.last_used_at&.after?(LAST_USED_PRECISION.ago)
37
+
38
+ token.update_column(:last_used_at, Time.current)
39
+ end
40
+
41
+ # The 401 and 403 challenge. It names the protected-resource metadata so a
42
+ # client can find the authorization server, and the scope to ask for.
43
+ def mcp_challenge(error: nil, scope: "read")
44
+ metadata = %(resource_metadata="#{request.base_url}/.well-known/oauth-protected-resource/mcp")
45
+
46
+ if error
47
+ %(Bearer error="#{error}", scope="#{scope}", #{metadata})
48
+ else
49
+ %(Bearer #{metadata}, scope="#{scope}")
50
+ end
51
+ end
52
+
53
+ def mcp_resource
54
+ "#{request.base_url}/mcp"
55
+ end
56
+
57
+ # The token's digest, so the limit follows the client and not a shared
58
+ # egress address. The raw token never becomes a cache key.
59
+ def mcp_rate_limit_key
60
+ token = bearer_token
61
+ token ? "token:#{AccessToken.digest(token)}" : "ip:#{request.remote_ip}"
62
+ end
63
+ end
@@ -0,0 +1,205 @@
1
+ # The MCP endpoint (generated by maquina:mcp): JSON-RPC over one POST /mcp,
2
+ # protocol revision 2026-07-28 only. Stateless: every request carries its
3
+ # protocol version in params._meta and mirrors it, the method and (for
4
+ # tools/call) the tool name in headers. There is no initialize, no
5
+ # Mcp-Session-Id and no SSE; GET and DELETE answer 405.
6
+ #
7
+ # A bearer token is not a cookie session, so Current.user stays nil here.
8
+ # Tools get the token's user through an Mcp::UserScope instead.
9
+ class McpController < ActionController::API
10
+ include McpAuthenticatable
11
+
12
+ SUPPORTED_VERSIONS = [Mcp::PROTOCOL_VERSION].freeze
13
+ PROTOCOL_VERSION_META = "io.modelcontextprotocol/protocolVersion"
14
+ CLIENT_CAPABILITIES_META = "io.modelcontextprotocol/clientCapabilities"
15
+ SERVER_INFO_META = "io.modelcontextprotocol/serverInfo"
16
+ BASE64_SENTINEL = /\A=\?base64\?(.*)\?=\z/
17
+ DISCOVER_TTL_MS = 3_600_000
18
+ TOOLS_TTL_MS = 300_000
19
+
20
+ # Every error this endpoint returns, with its JSON-RPC code and HTTP
21
+ # status. The codes are not interchangeable: an unknown tool or resource is
22
+ # -32602 (never -32002), an unknown method is -32601 with a 404, and a tool
23
+ # that fails is not an error at all but a result with isError: true.
24
+ # -32021 is defined for completeness; no v1 path needs a client capability.
25
+ # -32001 and -32000 are this server's auth and rate-limit codes.
26
+ ERRORS = {
27
+ parse_error: {code: -32_700, status: :bad_request, message: "Parse error: the body is not JSON"},
28
+ invalid_request: {code: -32_600, status: :bad_request, message: "Invalid request"},
29
+ method_not_found: {code: -32_601, status: :not_found, message: "Method not found"},
30
+ missing_meta: {code: -32_602, status: :bad_request, message: "Invalid params"},
31
+ invalid_params: {code: -32_602, status: :ok, message: "Invalid params"},
32
+ internal_error: {code: -32_603, status: :ok, message: "Internal error"},
33
+ header_mismatch: {code: -32_020, status: :bad_request, message: "Header mismatch"},
34
+ missing_required_client_capability: {code: -32_021, status: :bad_request, message: "Missing required client capability"},
35
+ unsupported_protocol_version: {code: -32_022, status: :bad_request, message: "Unsupported protocol version"},
36
+ unauthorized: {code: -32_001, status: :unauthorized, message: "Invalid or expired token"},
37
+ insufficient_scope: {code: -32_001, status: :forbidden, message: "This tool changes data and needs the write scope"},
38
+ rate_limited: {code: -32_000, status: :too_many_requests, message: "Too many requests; wait a minute and retry"}
39
+ }.freeze
40
+
41
+ wrap_parameters false
42
+
43
+ # Keyed on the token, not the address: agents share egress IPs and one turn
44
+ # sends several calls.
45
+ rate_limit to: 120, within: 1.minute, only: :create, by: -> { mcp_rate_limit_key },
46
+ with: -> { render_rpc_error(:rate_limited, headers: {"Retry-After" => "60"}) }
47
+
48
+ def create
49
+ body = parse_body
50
+ return render_rpc_error(:parse_error) if body == :unparseable
51
+ return render_rpc_error(:invalid_request, "Send one JSON-RPC request object; batches are not supported") unless body.is_a?(Hash)
52
+ return head :accepted unless body.key?("id")
53
+
54
+ @rpc_id = body["id"]
55
+ return render_rpc_error(:invalid_request, "id must be a string or an integer") unless @rpc_id.is_a?(String) || @rpc_id.is_a?(Integer)
56
+ return render_rpc_error(:invalid_request, %(jsonrpc must be "2.0")) unless body["jsonrpc"] == "2.0"
57
+
58
+ method = body["method"]
59
+ return render_rpc_error(:invalid_request, "method must be a string") unless method.is_a?(String)
60
+ return refuse_initialize if method == "initialize"
61
+
62
+ params = as_object(body["params"])
63
+ return if refused_meta?(params) || refused_headers?(method, params)
64
+
65
+ handle_rpc(method, params)
66
+ end
67
+
68
+ # GET and DELETE belonged to the SSE stream and the session, which this
69
+ # revision removed. Answered on purpose: a routing 404 reads as a wrong URL.
70
+ def method_not_allowed
71
+ response.set_header("Allow", "POST")
72
+ head :method_not_allowed
73
+ end
74
+
75
+ private
76
+
77
+ def handle_rpc(method, params)
78
+ case method
79
+ when "server/discover" then render_result(discover)
80
+ when "tools/list" then with_token { render_result(list_tools) }
81
+ when "tools/call" then with_token { call_tool(params) }
82
+ else render_rpc_error(:method_not_found, "Method not found: #{method}")
83
+ end
84
+ end
85
+
86
+ def discover
87
+ {supportedVersions: SUPPORTED_VERSIONS, capabilities: {tools: {}}, ttlMs: DISCOVER_TTL_MS, cacheScope: "public"}
88
+ end
89
+
90
+ # Private: the list depends on the token's user, so a shared cache must
91
+ # never hand it to another caller.
92
+ def list_tools
93
+ {tools: Mcp::ToolDefinitions.for(@mcp_user), ttlMs: TOOLS_TTL_MS, cacheScope: "private"}
94
+ end
95
+
96
+ def call_tool(params)
97
+ name = params["name"]
98
+ owner = Mcp::ToolDefinitions.owner(name, @mcp_user) if name.is_a?(String)
99
+ return render_rpc_error(:invalid_params, "Unknown tool: #{name}") unless owner
100
+ return refuse_insufficient_scope if owner::WRITE_TOOLS.include?(name) && !@access_token.scopes.include?("write")
101
+
102
+ Rails.logger.info("[MCP] tools/call #{name} user_id=#{@mcp_user.id}")
103
+ scope = Mcp::UserScope.new(@mcp_user, oauth_scopes: @access_token.scopes)
104
+ render_result(Mcp::Tools.call(name, params["arguments"], scope: scope))
105
+ rescue Mcp::Tools::InvalidParams => error
106
+ render_rpc_error(:invalid_params, error.message)
107
+ end
108
+
109
+ def with_token
110
+ if authenticate_mcp_token
111
+ yield
112
+ else
113
+ render_rpc_error(:unauthorized, headers: {"WWW-Authenticate" => mcp_challenge})
114
+ end
115
+ end
116
+
117
+ def refuse_insufficient_scope
118
+ render_rpc_error(:insufficient_scope,
119
+ headers: {"WWW-Authenticate" => mcp_challenge(error: "insufficient_scope", scope: "read write")})
120
+ end
121
+
122
+ # Legacy clients open with initialize and can show only this message, so it
123
+ # names the revision this server speaks.
124
+ def refuse_initialize
125
+ render_rpc_error(:method_not_found,
126
+ "This server speaks MCP #{Mcp::PROTOCOL_VERSION} only and has no initialize handshake. " \
127
+ "Send each request with params._meta[\"#{PROTOCOL_VERSION_META}\"] = \"#{Mcp::PROTOCOL_VERSION}\".",
128
+ data: {supported: SUPPORTED_VERSIONS})
129
+ end
130
+
131
+ def refused_meta?(params)
132
+ meta = as_object(params["_meta"])
133
+ version = meta[PROTOCOL_VERSION_META]
134
+
135
+ if !version.is_a?(String) || !meta[CLIENT_CAPABILITIES_META].is_a?(Hash)
136
+ render_rpc_error(:missing_meta, "params._meta must carry #{PROTOCOL_VERSION_META} and #{CLIENT_CAPABILITIES_META}")
137
+ elsif SUPPORTED_VERSIONS.exclude?(version)
138
+ render_rpc_error(:unsupported_protocol_version, data: {supported: SUPPORTED_VERSIONS, requested: version})
139
+ end
140
+
141
+ performed?
142
+ end
143
+
144
+ # The headers restate the body so an intermediary can route without parsing
145
+ # it. A disagreement is refused rather than guessed at.
146
+ def refused_headers?(method, params)
147
+ expected = {"MCP-Protocol-Version" => params["_meta"][PROTOCOL_VERSION_META], "Mcp-Method" => method}
148
+ expected["Mcp-Name"] = params["name"].to_s if method == "tools/call"
149
+
150
+ header, _ = expected.find { |name, value| header_value(name, request.headers[name]) != value }
151
+ return false unless header
152
+
153
+ if request.headers[header].nil?
154
+ render_rpc_error(:header_mismatch, "The #{header} header is required")
155
+ else
156
+ render_rpc_error(:header_mismatch, "The #{header} header does not match the request body")
157
+ end
158
+ true
159
+ end
160
+
161
+ # Mcp-Name carries a header-unsafe tool name as =?base64?…?=.
162
+ def header_value(header, sent)
163
+ match = BASE64_SENTINEL.match(sent) if sent && header == "Mcp-Name"
164
+ return sent unless match
165
+
166
+ match[1].unpack1("m0").force_encoding(Encoding::UTF_8)
167
+ rescue ArgumentError
168
+ nil
169
+ end
170
+
171
+ def parse_body
172
+ JSON.parse(request.raw_post)
173
+ rescue JSON::ParserError
174
+ :unparseable
175
+ end
176
+
177
+ # A client sending a string or an array where the spec says object gets an
178
+ # empty object, not a 500.
179
+ def as_object(value)
180
+ value.is_a?(Hash) ? value : {}
181
+ end
182
+
183
+ # Every result says it is complete and names the server: there is no
184
+ # handshake left to have said it once.
185
+ def render_result(result)
186
+ render json: {
187
+ jsonrpc: "2.0",
188
+ id: @rpc_id,
189
+ result: result.merge(resultType: "complete", _meta: {SERVER_INFO_META => server_info})
190
+ }
191
+ end
192
+
193
+ def render_rpc_error(key, message = nil, data: nil, headers: {})
194
+ error = ERRORS.fetch(key)
195
+ headers.each { |name, value| response.set_header(name, value) }
196
+
197
+ body = {code: error[:code], message: message || error[:message]}
198
+ body[:data] = data if data
199
+ render json: {jsonrpc: "2.0", id: @rpc_id, error: body}, status: error[:status]
200
+ end
201
+
202
+ def server_info
203
+ {name: Rails.application.class.module_parent_name.underscore.dasherize, version: Mcp::SERVER_VERSION}
204
+ end
205
+ end
@@ -0,0 +1,38 @@
1
+ module Mcp
2
+ # The tool list the model reads (generated by maquina:mcp), gathered from
3
+ # every module in app/models/mcp/tools/: by file name, then in each module's
4
+ # declaration order, so tools/list is the same on every call.
5
+ #
6
+ # Each module there owns its tools: DEFINITIONS (frozen JSON Schema
7
+ # 2020-12, written in plain English for the model, units stated),
8
+ # WRITE_TOOLS (names that need the write scope) and ADMIN_ONLY. maquina:mcp_tool
9
+ # writes to tools/app.rb; maquina:solid_errors and the other operational
10
+ # generators each write their own file.
11
+ module ToolDefinitions
12
+ TOOLS_GLOB = "app/models/mcp/tools/*.rb"
13
+
14
+ def self.modules
15
+ Dir[Rails.root.join(TOOLS_GLOB)].sort.map do |path|
16
+ "Mcp::Tools::#{File.basename(path, ".rb").camelize}".constantize
17
+ end
18
+ end
19
+
20
+ # Admin-only modules read operational data across every account, not the
21
+ # user's own: only someone with backstage access (User#backstage_access?,
22
+ # the backstage.emails list) and MCP enabled sees them. An account's admin
23
+ # role is not enough. For everyone else they do not exist.
24
+ def self.visible_modules(user)
25
+ modules.reject { |mod| mod::ADMIN_ONLY && !(user.backstage_access? && Mcp.enabled_for?(user)) }
26
+ end
27
+
28
+ def self.for(user)
29
+ visible_modules(user).flat_map { |mod| mod::DEFINITIONS }
30
+ end
31
+
32
+ # The visible module that declares the tool, or nil: an unknown name and a
33
+ # hidden one look the same.
34
+ def self.owner(name, user)
35
+ visible_modules(user).find { |mod| mod::DEFINITIONS.any? { |definition| definition[:name] == name } }
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,17 @@
1
+ module Mcp
2
+ # A failure the model reads and can act on (generated by maquina:mcp).
3
+ # Raised inside a tool, it becomes a tool result with isError: true and the
4
+ # message as its text, not a JSON-RPC error: write the message for the model.
5
+ #
6
+ # raise Mcp::ToolError, "status must be draft or published"
7
+ # raise Mcp::ToolError.not_found
8
+ class ToolError < StandardError
9
+ # One message for a record that does not exist and for one that belongs to
10
+ # someone else, so the tools never tell a caller which ids exist.
11
+ NOT_FOUND = "Not found: no record with that id is available to this connection."
12
+
13
+ def self.not_found
14
+ new(NOT_FOUND)
15
+ end
16
+ end
17
+ end