stateless-mcp-rails 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d41343376a7f17949bbde534012b83b287aa9f833b066d9a61560009f5be419d
4
+ data.tar.gz: d60c6604a3b37a53937383c5a69ee8beeecdb2622e4b7a8b4838b8f83d7984ee
5
+ SHA512:
6
+ metadata.gz: 356d860719f2539f74f485642333305214a335a419e5afc751d94af3ee42ec93835ccd9f0ec913d97ae930af4c1d8ff5073a5d67f3d5b40e8547ca773367d60d
7
+ data.tar.gz: 3052880407f485fef014e07a8e6697ccad0b02b57bae8780adbbfc57576312face3850f7b0fd770d696469ceb32cb136091bc01af4117403c97376e3c51ef18f
data/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ Changes to the `stateless-mcp-rails` gem. It's released at the same version as `stateless-mcp`, whose [changelog](../stateless-mcp/CHANGELOG.md) covers the protocol. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.0.1] - 2026-10-19
8
+
9
+ First release: MCP servers declared in Rails routes, with tools as controller actions.
10
+
11
+ - An engine building a default server from `config.stateless_mcp`, and the `mcp_server`, `mcp_resource`, `mcp_member` and `mcp_tool` route macros.
12
+ - `server/discover` and `tools/list` answered from config and routes, each server listing only its own tools.
13
+ - Tool calls: arguments checked against the declared schema and read through `tool_params`, refusals the model can act on, and internal errors reported to `Rails.error`.
14
+ - `paginate_list` and `paginate_text`, plus keyset paging for ActiveRecord from `require "stateless_mcp/rails/active_record"`.
15
+ - `rake mcp:tools`, listing each server's tools.
16
+ - Boot refused until `parent_controller` names the app's own base controller, or `allow_unauthenticated` is `true`.
17
+
18
+ [Unreleased]: https://github.com/Jamedjo/stateless-mcp/compare/v0.0.1...HEAD
19
+ [0.0.1]: https://github.com/Jamedjo/stateless-mcp/tree/v0.0.1/stateless-mcp-rails
data/LICENSE-APACHE ADDED
@@ -0,0 +1,203 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
data/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 James Edwards-Jones
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # stateless-mcp-rails
2
+
3
+ Rails support for [stateless-mcp](https://github.com/Jamedjo/stateless-mcp): [Model Context Protocol](https://modelcontextprotocol.io/specification/2026-07-28) tools as ordinary routes and controller actions, served without sessions.
4
+
5
+ > **Status:** early. Releases before 1.0 may change the API.
6
+
7
+ ```ruby
8
+ gem "stateless-mcp-rails"
9
+ ```
10
+
11
+ The documentation is in the [main README](https://github.com/Jamedjo/stateless-mcp#readme) and the [Rails guide](https://github.com/Jamedjo/stateless-mcp/blob/main/docs/rails.md).
12
+
13
+ Licensed under either of Apache-2.0 or MIT, at your option.
@@ -0,0 +1,11 @@
1
+ module StatelessMcp
2
+ module Rails
3
+ # Answers the protocol's own methods, such as server/discover and
4
+ # tools/list, for every server drawn with mcp_server. It inherits from
5
+ # config.stateless_mcp.parent_controller, so whatever guards the app's
6
+ # tools guards these too.
7
+ class ServerController < ::Rails.application.config.stateless_mcp.parent_controller.constantize
8
+ include ServerActions
9
+ end
10
+ end
11
+ end
@@ -0,0 +1 @@
1
+ require "stateless_mcp/rails"
@@ -0,0 +1,41 @@
1
+ require "active_record"
2
+ require "stateless_mcp/rails"
3
+
4
+ module StatelessMcp
5
+ module Rails
6
+ # Keyset paging for ActiveRecord, newest first. Optional, so neither gem
7
+ # depends on ActiveRecord: an app that wants it requires this file and
8
+ # includes the module beside StatelessMcp::Rails::Controller.
9
+ #
10
+ # require "stateless_mcp/rails/active_record"
11
+ #
12
+ # class Mcp::BaseController < ActionController::API
13
+ # include StatelessMcp::Rails::Controller
14
+ # include StatelessMcp::Rails::RecordPagination
15
+ # end
16
+ module RecordPagination
17
+ private
18
+
19
+ # One page of records, newest first by (created_at, id), and the
20
+ # next_cursor for the page after. Each page continues after the last
21
+ # record of the one before, so a deep page costs the same as the first
22
+ # and records added meanwhile don't shift it.
23
+ def paginate(records, limit: page_limit)
24
+ records = records.reorder(created_at: :desc, id: :desc)
25
+ records = after_cursor(records, *Cursor.decode(tool_params[:cursor], count: 2)) if tool_params[:cursor].present?
26
+ rows = records.limit(limit + 1).to_a
27
+ page = rows.first(limit)
28
+ [page, (Cursor.encode(page.last.created_at.iso8601(6), page.last.id) if rows.size > limit)]
29
+ end
30
+
31
+ # The id keeps its JSON type, so integer and string keys both work.
32
+ def after_cursor(records, created_at, id)
33
+ raise Cursor::Invalid unless id.is_a?(Integer) || id.is_a?(String)
34
+ created_at = Time.iso8601(created_at.to_s)
35
+ records.where(created_at: ...created_at).or(records.where(created_at: created_at, id: ...id))
36
+ rescue ArgumentError
37
+ raise Cursor::Invalid
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,143 @@
1
+ module StatelessMcp
2
+ module Rails
3
+ # Turns a controller's actions into MCP tools. Include it in the base
4
+ # controller the app's tools inherit from, declare each tool beside its
5
+ # action, read its arguments from tool_params, and answer with render_tool
6
+ # or refuse:
7
+ #
8
+ # tool :show, "Gets one note.", title: "Get a note" do
9
+ # argument :note_id, :integer, "The note id from list_notes", required: true
10
+ # end
11
+ # def show
12
+ # note = Note.find_by(id: tool_params[:note_id]) or return refuse("No note #{tool_params[:note_id]}")
13
+ # render_tool id: note.id, title: note.title
14
+ # end
15
+ module Controller
16
+ extend ActiveSupport::Concern
17
+
18
+ included do
19
+ class_attribute :mcp_tools, instance_writer: false, default: {}
20
+ # MCP clients accept JSON or an event stream, and every answer goes back
21
+ # as JSON whichever they listed first.
22
+ prepend_before_action { request.format = :json }
23
+ before_action :check_tool_arguments, if: :tool_call?
24
+ rescue_from StandardError, with: :internal_error
25
+ rescue_from InvalidArgument, with: ->(error) { refuse(error.message) }
26
+ rescue_from Cursor::Invalid, with: -> { refuse("cursor must be a next_cursor from an earlier result") }
27
+ end
28
+
29
+ class_methods do
30
+ # Declares the tool an action serves, as tools/list shows it. The block
31
+ # declares its arguments; see StatelessMcp::ToolDeclaration.
32
+ def tool(action, description, title:, annotations: ToolDeclaration::READ_ONLY, &arguments)
33
+ self.mcp_tools = mcp_tools.merge(action.to_s => ToolDeclaration.new(title: title, description: description, annotations: annotations, &arguments))
34
+ end
35
+
36
+ def mcp_tool_declaration(action)
37
+ mcp_tools.fetch(action.to_s) { raise UndeclaredTool, "#{name}##{action} is routed as a tool but declares none; declare it with `tool :#{action}, ...`" }
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ # The server this request was routed to.
44
+ def mcp_server
45
+ request.get_header(Server::ENV_KEY) or raise "No StatelessMcp::Middleware serves #{request.path}; is the server's middleware in the app's stack?"
46
+ end
47
+
48
+ # The parsed JSON-RPC body.
49
+ def mcp_request
50
+ request.get_header(REQUEST_ENV_KEY) || {}
51
+ end
52
+
53
+ def tool_call?
54
+ params[:mcp_tool].present?
55
+ end
56
+
57
+ def tool_declaration
58
+ self.class.mcp_tool_declaration(action_name)
59
+ end
60
+
61
+ # Strong parameters permitting exactly the declared arguments.
62
+ def tool_params
63
+ @tool_params ||= params.fetch(:params, {}).fetch(:arguments, {}).permit(*permitted_arguments)
64
+ end
65
+
66
+ # Reads a :datetime argument, refusing anything that isn't ISO 8601.
67
+ def tool_time(name)
68
+ value = tool_params[name]
69
+ value.blank? ? nil : Time.zone.iso8601(value)
70
+ rescue ArgumentError
71
+ raise InvalidArgument, "#{name} must be an ISO 8601 date or time, like 2026-10-01 or 2026-10-01T09:00:00Z"
72
+ end
73
+
74
+ # The page size the call asked for, held to the server's limits.
75
+ def page_limit
76
+ Pagination.limit(tool_params[:limit], mcp_server)
77
+ end
78
+
79
+ # One page of a list, and the next_cursor for the page after.
80
+ def paginate_list(items)
81
+ Pagination.list(items, cursor: tool_params[:cursor], limit: page_limit)
82
+ end
83
+
84
+ # A long text in parts of part_size characters, and the next_cursor for
85
+ # the part after. The block reads a slice of the text from a start
86
+ # position and length.
87
+ def paginate_text(part_size, &read)
88
+ Pagination.text(tool_params[:cursor], part_size, &read)
89
+ end
90
+
91
+ def render_tool(payload)
92
+ render_result Result.tool(payload)
93
+ end
94
+
95
+ # A refusal the model can read and act on, rather than a protocol error.
96
+ def refuse(message)
97
+ render_result Result.refusal(message)
98
+ end
99
+
100
+ def render_result(result)
101
+ render json: Rpc.success(mcp_request["id"], result)
102
+ end
103
+
104
+ def render_rpc_error(code, message, data: nil)
105
+ render json: Rpc.error(mcp_request["id"], code, message, data: data), status: Rpc.status_for(code)
106
+ end
107
+
108
+ # The arguments are checked against the raw JSON, before strong
109
+ # parameters coerce anything. Arguments that aren't an object make the
110
+ # call itself malformed, which is a protocol error.
111
+ def check_tool_arguments
112
+ arguments = mcp_request.dig("params", "arguments") || {}
113
+ return render_rpc_error(Rpc::ErrorCode::INVALID_PARAMS, "arguments must be an object") unless arguments.is_a?(Hash)
114
+ schema = tool_declaration.input_schema(mcp_server)
115
+ missing = schema.missing_required_arguments(arguments)
116
+ return refuse("Missing required arguments: #{missing.join(", ")}") if missing.any?
117
+ schema.validate_arguments(arguments)
118
+ rescue MCP::Tool::InputSchema::ValidationError => error
119
+ refuse(error.message)
120
+ end
121
+
122
+ def permitted_arguments
123
+ tool_declaration.input_schema(mcp_server).to_h.fetch(:properties, {}).map do |name, property|
124
+ case property[:type]
125
+ when "array" then { name => [] }
126
+ when "object" then { name => {} }
127
+ else name
128
+ end
129
+ end
130
+ end
131
+
132
+ # Errors Rails answers with a status of its own, such as a rate limit's
133
+ # 429, keep it. Anything else reaches the client only as "Internal error",
134
+ # so its cause has to reach the app's error reporting from here or it is
135
+ # lost.
136
+ def internal_error(exception)
137
+ raise exception if exception.is_a?(ActionController::ActionControllerError)
138
+ ::Rails.error.report(exception, source: "stateless_mcp")
139
+ render_rpc_error(Rpc::ErrorCode::INTERNAL_ERROR, "Internal error")
140
+ end
141
+ end
142
+ end
143
+ end
@@ -0,0 +1,36 @@
1
+ module StatelessMcp
2
+ module Rails
3
+ # Builds the default server from config.stateless_mcp and puts its
4
+ # middleware on the app's stack. An engine rather than a plain railtie, so
5
+ # the server controller under app/controllers is autoloaded and can
6
+ # inherit from a controller of the app's.
7
+ class Engine < ::Rails::Engine
8
+ config.stateless_mcp = ActiveSupport::OrderedOptions.new
9
+ # Every StatelessMcp::Server setting can be set here too, such as path,
10
+ # name and max_body_bytes. The server controller inherits from this one,
11
+ # so the app's sign-in and rate limits cover it too. Left as the default,
12
+ # the app doesn't boot unless allow_unauthenticated is true.
13
+ config.stateless_mcp.parent_controller = DEFAULT_PARENT_CONTROLLER
14
+ config.stateless_mcp.allow_unauthenticated = false
15
+
16
+ rake_tasks do
17
+ namespace :mcp do
18
+ desc "Lists each MCP server's tools. VERBOSE=1 adds each tool's argument schema"
19
+ task tools: :environment do
20
+ puts ToolsReport.new(::Rails.application.routes, verbose: ENV["VERBOSE"].present?)
21
+ end
22
+ end
23
+ end
24
+
25
+ initializer "stateless_mcp.routing" do
26
+ ActionDispatch::Routing::Mapper.include(Routing)
27
+ end
28
+
29
+ # After the app's own initializers, which may set config.stateless_mcp.
30
+ initializer "stateless_mcp.default_server", after: :load_config_initializers do |app|
31
+ StatelessMcp::Rails.default_server = StatelessMcp::Rails.build_default_server(app.config.stateless_mcp.to_h, default_name: app.class.module_parent_name.underscore)
32
+ app.config.middleware.use Middleware, server: StatelessMcp::Rails.default_server
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,121 @@
1
+ module StatelessMcp
2
+ module Rails
3
+ # Route macros for config/routes.rb. Every MCP request is a POST to the
4
+ # server's path, told apart by its Mcp-Method and Mcp-Name headers:
5
+ #
6
+ # mcp_server module: "mcp" do
7
+ # mcp_resource :notes, only: [:index, :show] do
8
+ # mcp_member :body
9
+ # end
10
+ # mcp_tool "search", to: "search#show"
11
+ # end
12
+ #
13
+ # draws list_notes, get_note, get_note_body and search as tools, routed to
14
+ # mcp/notes#index, #show, #body and mcp/search#show. tools/list is built
15
+ # from these routes, so a tool is listed exactly when it is routed.
16
+ module Routing
17
+ SERVER_CONTROLLER = "stateless_mcp/rails/server"
18
+
19
+ # The servers each route set draws, by path. An app has one route set, so
20
+ # holding on to them costs nothing.
21
+ DRAWN_SERVERS = Hash.new { |sets, route_set| sets[route_set] = {} }.compare_by_identity
22
+
23
+ # Matches a request by the headers the middleware has already checked
24
+ # against its body.
25
+ class Constraint
26
+ def initialize(method, name: nil)
27
+ @method = method
28
+ @name = name
29
+ end
30
+
31
+ def matches?(request)
32
+ request.headers["Mcp-Method"] == @method && (@name.nil? || request.headers["Mcp-Name"] == @name)
33
+ end
34
+ end
35
+
36
+ # Each tool routed to a server's path, as [name, controller class, action],
37
+ # in the order the routes are drawn.
38
+ def self.tools(server, route_set)
39
+ route_set.routes.filter_map do |route|
40
+ name = route.defaults[:mcp_tool]
41
+ next unless name && route.path.spec.to_s == server.path
42
+ [name, "#{route.defaults[:controller]}_controller".camelize.constantize, route.defaults[:action]]
43
+ end
44
+ end
45
+
46
+ # Each tool's tools/list entry, with the controller and action it's
47
+ # routed to. tools/list and `rake mcp:tools` both read this, so the two
48
+ # always agree.
49
+ def self.listed_tools(server, route_set)
50
+ tools(server, route_set).map do |name, controller, action|
51
+ [controller.mcp_tool_declaration(action).to_h(name, server), controller, action]
52
+ end
53
+ end
54
+
55
+ # Each server drawn with mcp_server and still routed, in the order the
56
+ # routes are drawn. Reading the routes first loads them if Rails has
57
+ # deferred that.
58
+ def self.servers(route_set)
59
+ routed_paths = route_set.routes.map { |route| route.path.spec.to_s }
60
+ DRAWN_SERVERS[route_set].values.select { |server| routed_paths.include?(server.path) }
61
+ end
62
+
63
+ # Draws a server's routes: its tools, from the block, and the protocol's
64
+ # own methods, answered by the controller given. Options such as module:
65
+ # scope the tools' controllers but not the server controller. The server
66
+ # is the default one built from config.stateless_mcp unless another is
67
+ # given.
68
+ def mcp_server(server = nil, controller: SERVER_CONTROLLER, **options)
69
+ server ||= StatelessMcp::Rails.default_server
70
+ raise ArgumentError, "mcp_server draws at its server's own path, #{server.path}, so it can't be inside a path scope" if @scope[:path]
71
+ @mcp_server = server
72
+ DRAWN_SERVERS[@set][server.path] = server
73
+ scope(as: nil, format: false) do
74
+ mcp_method MCP::Methods::SERVER_DISCOVER, to: "#{controller}#discover"
75
+ mcp_method MCP::Methods::TOOLS_LIST, to: "#{controller}#tools"
76
+ scope(**options) { yield } if block_given?
77
+ post server.path, to: "#{controller}#unknown_method", as: nil
78
+ end
79
+ ensure
80
+ @mcp_server = nil
81
+ end
82
+
83
+ # A tool for each action, named by the server's tool_verbs: index on
84
+ # notes is list_notes, show is get_note.
85
+ def mcp_resource(resources, only:)
86
+ @mcp_resource = resources.to_s
87
+ Array(only).each do |action|
88
+ verb = current_mcp_server.tool_verbs[action.to_sym] or raise ArgumentError, "No tool verb for :#{action}; add one to tool_verbs, or route it with mcp_member or mcp_tool"
89
+ noun = action.to_sym == :index ? @mcp_resource : @mcp_resource.singularize
90
+ mcp_tool "#{verb}_#{noun}", to: "#{@mcp_resource}##{action}"
91
+ end
92
+ yield if block_given?
93
+ ensure
94
+ @mcp_resource = nil
95
+ end
96
+
97
+ # A tool reading one more thing about a member of the resource it's
98
+ # drawn in, named get_<singular>_<action>.
99
+ def mcp_member(action, verb: "get")
100
+ raise ArgumentError, "mcp_member belongs inside an mcp_resource block" unless @mcp_resource
101
+ mcp_tool "#{verb}_#{@mcp_resource.singularize}_#{action}", to: "#{@mcp_resource}##{action}"
102
+ end
103
+
104
+ # The tool name is kept as a route default, which is where tools/list
105
+ # reads it back from.
106
+ def mcp_tool(name, to:)
107
+ post current_mcp_server.path, to: to, constraints: Constraint.new(MCP::Methods::TOOLS_CALL, name: name.to_s), defaults: { mcp_tool: name.to_s }, as: nil
108
+ end
109
+
110
+ def mcp_method(method, to:)
111
+ post current_mcp_server.path, to: to, constraints: Constraint.new(method), as: nil
112
+ end
113
+
114
+ private
115
+
116
+ def current_mcp_server
117
+ @mcp_server or raise ArgumentError, "MCP tools and methods are drawn inside an mcp_server block"
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,37 @@
1
+ module StatelessMcp
2
+ module Rails
3
+ # The protocol's own methods, which mcp_server routes to the server
4
+ # controller. The gem's StatelessMcp::Rails::ServerController includes
5
+ # this; an app that writes its own server controller includes it there.
6
+ module ServerActions
7
+ extend ActiveSupport::Concern
8
+
9
+ include Controller
10
+
11
+ def discover
12
+ render_result Result.discover(mcp_server, capabilities: capabilities)
13
+ end
14
+
15
+ def tools
16
+ tools = Routing.listed_tools(mcp_server, _routes).map(&:first)
17
+ render_result Result.complete({ tools: tools }, cacheable: true)
18
+ end
19
+
20
+ # Any request no route claimed. A notification needs no answer, and a
21
+ # tool that isn't routed is a bad argument to tools/call rather than an
22
+ # unknown method.
23
+ def unknown_method
24
+ method = mcp_request["method"]
25
+ return head(:accepted) if MCP::Methods.notification?(method)
26
+ return render_rpc_error(Rpc::ErrorCode::INVALID_PARAMS, "Unknown tool: #{mcp_request.dig("params", "name")}") if method == MCP::Methods::TOOLS_CALL
27
+ render_rpc_error(Rpc::ErrorCode::METHOD_NOT_FOUND, "Method not found", data: method)
28
+ end
29
+
30
+ private
31
+
32
+ def capabilities
33
+ { tools: {} }
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,42 @@
1
+ module StatelessMcp
2
+ module Rails
3
+ # The text `rake mcp:tools` prints: each server's tools as a table, with
4
+ # each tool's argument schema on the line below it when verbose.
5
+ class ToolsReport
6
+ HEADINGS = ["Tool", "Title", "Action", "Read-only"].freeze
7
+
8
+ def initialize(route_set, verbose: false)
9
+ @route_set = route_set
10
+ @verbose = verbose
11
+ end
12
+
13
+ def to_s
14
+ Routing.servers(@route_set).map { |server| server_section(server) }.join("\n")
15
+ end
16
+
17
+ private
18
+
19
+ def server_section(server)
20
+ tools = Routing.listed_tools(server, @route_set)
21
+ return "#{server.name} (#{server.path})\n No tools\n" if tools.empty?
22
+ rows = tools.map { |entry, controller, action| row(entry, controller, action) }
23
+ widths = HEADINGS.each_index.map { |column| ([HEADINGS] + rows).map { |cells| cells[column].length }.max }
24
+ lines = [format_row(HEADINGS, widths)]
25
+ rows.zip(tools) do |cells, (entry, _, _)|
26
+ lines << format_row(cells, widths)
27
+ lines << " #{JSON.generate(entry[:inputSchema].except(:"$schema"))}" if @verbose
28
+ end
29
+ "#{server.name} (#{server.path})\n#{lines.join("\n")}\n"
30
+ end
31
+
32
+ def row(entry, controller, action)
33
+ read_only = entry.dig(:annotations, :readOnlyHint)
34
+ [entry[:name], entry[:title].to_s, "#{controller.controller_path}##{action}", read_only.nil? ? "" : (read_only ? "yes" : "no")]
35
+ end
36
+
37
+ def format_row(cells, widths)
38
+ " #{cells.zip(widths).map { |cell, width| cell.ljust(width) }.join(" ")}".rstrip
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,55 @@
1
+ require "stateless_mcp"
2
+ require "rails"
3
+ require "action_controller"
4
+
5
+ module StatelessMcp
6
+ # Rails support: a tool is a controller action, routed by the Mcp-Method and
7
+ # Mcp-Name headers. Inside StatelessMcp, `Rails` names this module, so the
8
+ # framework itself is always written `::Rails`.
9
+ module Rails
10
+ # Raised when a routed action has no tool declaration to list it by.
11
+ UndeclaredTool = Class.new(StandardError)
12
+
13
+ # Raised at boot when the app has set neither parent_controller nor
14
+ # allow_unauthenticated, as the tools would be open to anyone.
15
+ AuthenticationNotConfigured = Class.new(Server::Invalid)
16
+
17
+ DEFAULT_PARENT_CONTROLLER = "ActionController::API"
18
+
19
+ class << self
20
+ # The server built from config.stateless_mcp at boot. Only the engine
21
+ # sets it, and only `mcp_server` without a server argument reads it.
22
+ attr_writer :default_server
23
+
24
+ def default_server
25
+ @default_server or raise "The default MCP server is built from config.stateless_mcp when the app boots, and it hasn't booted yet"
26
+ end
27
+
28
+ # The default server, from the settings in config.stateless_mcp.
29
+ def build_default_server(settings, default_name:)
30
+ check_authentication(settings)
31
+ server_settings = settings.except(:parent_controller, :allow_unauthenticated)
32
+ server_settings[:name] ||= default_name
33
+ Server.new(**server_settings)
34
+ end
35
+
36
+ private
37
+
38
+ # A parent controller of the app's own is trusted to authenticate. The
39
+ # gem can't tell whether it does, only that the app has chosen one.
40
+ def check_authentication(settings)
41
+ return if settings[:allow_unauthenticated] == true
42
+ return if settings.fetch(:parent_controller, DEFAULT_PARENT_CONTROLLER).to_s != DEFAULT_PARENT_CONTROLLER
43
+ raise AuthenticationNotConfigured, "config.stateless_mcp.parent_controller is #{DEFAULT_PARENT_CONTROLLER}, so anyone who can reach the MCP endpoint can call every tool. " \
44
+ "Set config.stateless_mcp.parent_controller to a controller that authenticates, such as \"Mcp::BaseController\", " \
45
+ "or set config.stateless_mcp.allow_unauthenticated = true for a server that is open on purpose."
46
+ end
47
+ end
48
+ end
49
+ end
50
+
51
+ require_relative "rails/routing"
52
+ require_relative "rails/controller"
53
+ require_relative "rails/server_actions"
54
+ require_relative "rails/tools_report"
55
+ require_relative "rails/engine"
metadata ADDED
@@ -0,0 +1,116 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: stateless-mcp-rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - James Edwards-Jones
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2026-10-19 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: stateless-mcp
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - '='
17
+ - !ruby/object:Gem::Version
18
+ version: 0.0.1
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - '='
24
+ - !ruby/object:Gem::Version
25
+ version: 0.0.1
26
+ - !ruby/object:Gem::Dependency
27
+ name: actionpack
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '7.1'
33
+ - - "<"
34
+ - !ruby/object:Gem::Version
35
+ version: '9'
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '7.1'
43
+ - - "<"
44
+ - !ruby/object:Gem::Version
45
+ version: '9'
46
+ - !ruby/object:Gem::Dependency
47
+ name: railties
48
+ requirement: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '7.1'
53
+ - - "<"
54
+ - !ruby/object:Gem::Version
55
+ version: '9'
56
+ type: :runtime
57
+ prerelease: false
58
+ version_requirements: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: '7.1'
63
+ - - "<"
64
+ - !ruby/object:Gem::Version
65
+ version: '9'
66
+ description: 'Rails support for stateless-mcp: a tool is a controller action, routed
67
+ by the Mcp-Method and Mcp-Name headers of the 2026-07-28 Model Context Protocol,
68
+ and tools/list is drawn from the routes.'
69
+ email:
70
+ - git@jamedjo.co.uk
71
+ executables: []
72
+ extensions: []
73
+ extra_rdoc_files: []
74
+ files:
75
+ - CHANGELOG.md
76
+ - LICENSE-APACHE
77
+ - LICENSE-MIT
78
+ - README.md
79
+ - app/controllers/stateless_mcp/rails/server_controller.rb
80
+ - lib/stateless-mcp-rails.rb
81
+ - lib/stateless_mcp/rails.rb
82
+ - lib/stateless_mcp/rails/active_record.rb
83
+ - lib/stateless_mcp/rails/controller.rb
84
+ - lib/stateless_mcp/rails/engine.rb
85
+ - lib/stateless_mcp/rails/routing.rb
86
+ - lib/stateless_mcp/rails/server_actions.rb
87
+ - lib/stateless_mcp/rails/tools_report.rb
88
+ homepage: https://github.com/Jamedjo/stateless-mcp
89
+ licenses:
90
+ - MIT
91
+ - Apache-2.0
92
+ metadata:
93
+ homepage_uri: https://github.com/Jamedjo/stateless-mcp
94
+ source_code_uri: https://github.com/Jamedjo/stateless-mcp/tree/v0.0.1/stateless-mcp-rails
95
+ changelog_uri: https://github.com/Jamedjo/stateless-mcp/blob/main/stateless-mcp-rails/CHANGELOG.md
96
+ documentation_uri: https://github.com/Jamedjo/stateless-mcp/blob/main/README.md
97
+ bug_tracker_uri: https://github.com/Jamedjo/stateless-mcp/issues
98
+ rubygems_mfa_required: 'true'
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '3.2'
107
+ required_rubygems_version: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: '0'
112
+ requirements: []
113
+ rubygems_version: 3.6.7
114
+ specification_version: 4
115
+ summary: Model Context Protocol tools as ordinary Rails routes and controller actions
116
+ test_files: []