Skip to content
Back to search

mcp_on_ruby

💎 A Ruby implementation of the Model Context Protocol

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/nagstler--mcp-on-ruby/badge.svg)](/listings/nagstler--mcp-on-ruby)

HTML

<a href="/listings/nagstler--mcp-on-ruby"><img src="/api/listings/nagstler--mcp-on-ruby/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Add to your `Gemfile`:

gem 'mcp_on_ruby'

Then run:

bundle install
rails generate mcp_on_ruby:install

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 460 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <div align="center">
  2. # MCP on Ruby
  3. **Make your Rails app usable by AI agents.**
  4. Your existing controllers become [Model Context Protocol](https://modelcontextprotocol.io) tools, running through<br>
  5. the same authentication, policies, params, and JSON you already ship.
  6. [![Gem Version](https://img.shields.io/gem/v/mcp_on_ruby)](https://rubygems.org/gems/mcp_on_ruby)
  7. [![CI](https://github.com/nagstler/mcp_on_ruby/actions/workflows/ci.yml/badge.svg)](https://github.com/nagstler/mcp_on_ruby/actions/workflows/ci.yml)
  8. [![Coverage](https://qlty.sh/gh/nagstler/projects/mcp_on_ruby/coverage.svg)](https://qlty.sh/gh/nagstler/projects/mcp_on_ruby)
  9. [![Maintainability](https://qlty.sh/gh/nagstler/projects/mcp_on_ruby/maintainability.svg)](https://qlty.sh/gh/nagstler/projects/mcp_on_ruby)
  10. [![Ruby](https://img.shields.io/badge/ruby-3.2%2B-CC342D)](#compatibility)
  11. [![Rails](https://img.shields.io/badge/rails-7.1%20%E2%80%93%208.1-D30001)](#compatibility)
  12. [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE.txt)
  13. [Quick start](#quick-start) ·
  14. [How it works](#how-it-works) ·
  15. [Guides](#guides) ·
  16. [Configuration](#configuration) ·
  17. [Testing](#testing)
  18. </div>
  19. ---
  20. ```ruby
  21. class OrdersController < ApplicationController
  22. before_action :authenticate_user!
  23. mcp_tool :index, description: "Search the current user's orders",
  24. params: { status: { type: :string, enum: %w[pending paid shipped] } }
  25. mcp_tool :show, description: "Fetch one order by id"
  26. def index
  27. render json: current_user.orders.where(params.permit(:status))
  28. end
  29. def show
  30. render json: current_user.orders.find(params[:id])
  31. end
  32. end
  33. ```
  34. That's the whole integration. Claude, Cursor, or any MCP client can now search and read orders **as the signed-in user**. Your `before_action` authenticates the agent, your scopes and policies decide what it can see, and your existing JSON comes back to it. You don't write new tool classes or a second permission system.
  35. ## Why MCP on Ruby
  36. Most MCP libraries ask you to build a parallel API for agents: new tool classes, new argument parsing, new authorization checks. Over time that second API drifts from the real one, and every rule has to be secured twice.
  37. MCP on Ruby takes the opposite approach. **Your app already has an API: your controllers.** MCP on Ruby makes it callable by agents.
  38. - **One source of truth.** Agents go through the same routes, filters, policies, validations, and serializers as your users.
  39. - **Real identity.** Every tool call runs as a real user, using the auth you already have: API tokens, Devise, or Warden.
  40. - **Safe by default.** Actions that change data must be marked `write: true`, and every tool tells the client whether it is read-only or destructive.
  41. - **Local and remote.** Serve Streamable HTTP in production, and stdio for Claude Code, Claude Desktop, and Cursor on your machine.
  42. - **Built on the official SDK.** The protocol layer is the official [`mcp`](https://github.com/modelcontextprotocol/ruby-sdk) gem, so protocol updates arrive without a rewrite.
  43. - **Works with the Rails you run today.** Rails 7.1 through 8.1 on Ruby 3.2+.
  44. ## Quick start
  45. **1. Install**
  46. ```bash
  47. bundle add mcp_on_ruby
  48. bin/rails generate mcp_on_ruby:install
  49. ```
  50. The generator creates `config/initializers/mcp_on_ruby.rb` and mounts the endpoint:
  51. ```ruby
  52. # config/routes.rb
  53. mount McpOnRuby::Engine, at: "/mcp"
  54. ```
  55. **2. Expose some actions**
  56. ```bash
  57. bin/rails generate mcp_on_ruby:expose products index show create
  58. ```
  59. This adds `mcp_tool` declarations to `ProductsController`, with a params schema for `create` built from the model's columns. Edit the descriptions: they are what the agent reads. Then check what agents will see:
  60. ```console
  61. $ bin/rails mcp:tools
  62. TOOL ACTION VERB PATH ACCESS
  63. products_create ProductsController#create POST /products write
  64. products_index ProductsController#index GET /products read-only
  65. products_show ProductsController#show GET /products/:id read-only
  66. ```
  67. **3. Connect an agent**
  68. Over HTTP, sending a token your app already accepts:
  69. ```bash
  70. claude mcp add --transport http my-app http://localhost:3000/mcp \
  71. --header "Authorization: Bearer $MY_APP_API_TOKEN"
  72. ```
  73. Or locally over stdio, acting as a user you choose ([set up `stdio_user`](#authentication) first):
  74. ```bash
  75. claude mcp add my-app -e MCP_USER=alice@example.com -- bin/rails mcp:stdio
  76. ```
  77. Then ask: *"Which of my products cost more than $50?"*
  78. ## How it works
  79. <p align="center">
  80. <picture>
  81. <source media="(prefers-color-scheme: dark)" srcset="docs/assets/how-it-works-dark.svg">
  82. <img src="docs/assets/how-it-works.svg" width="960" alt="An MCP client sends a tool call over HTTP or stdio to the official mcp gem, which hands it to MCP on Ruby. MCP on Ruby runs it as an ordinary Rails request through your app, as the caller, and the JSON response comes back as the tool result.">
  83. </picture>
  84. </p>
  85. Each tool call becomes an ordinary request through your full middleware stack. Anything that protects your API, including `rate_limit`, Rack::Attack, tenant scoping, and audit logging, protects agent traffic too.
  86. HTTP is served statelessly: every request is self-contained, so any Puma worker or server behind your load balancer can handle any MCP request, with no sticky sessions.
  87. ## Guides
  88. ### Declaring tools
  89. ```ruby
  90. mcp_tool :index,
  91. description: "Search products by name", # required: what the agent reads
  92. title: "Search products", # optional display name
  93. name: "search_products", # optional; defaults to "products_index"
  94. params: {
  95. q: :string, # shorthand
  96. sort: { type: :string, enum: %w[name price], default: "name" },
  97. limit: { type: :integer, minimum: 1, maximum: 100 }
  98. }
  99. ```
  100. Path parameters such as `:id` in `/products/:id` are read from your routes and added to the schema as required parameters. You don't declare them.
  101. Use a block for nested input:
  102. ```ruby
  103. mcp_tool :create, description: "Place an order", write: true do
  104. param :order, required: true do
  105. param :sku, type: :string, required: true
  106. param :quantity, type: :integer, minimum: 1
  107. param :tags, type: :array, items: :string
  108. param :note, type: :string, nullable: true
  109. end
  110. end
  111. ```
  112. Supported types: `:string`, `:integer`, `:number`, `:boolean`, `:array`, `:object`, `:null`, or an array of them. Options use Ruby names for JSON Schema keywords: `description`, `enum`, `default`, `format`, `pattern`, `minimum`, `maximum`, `min_length`, `max_length`, `min_items`, `max_items`, `unique_items`, and more. Unknown types and options raise immediately, so typos don't ship.
  113. The official SDK validates arguments against this schema before your controller runs. Arguments reach `params` exactly as they would from a JSON client, so strong params work unchanged. Read tools receive them as query parameters, write tools as a JSON body.
  114. ### Authentication
  115. MCP on Ruby never asks you to build a new auth system. It hands the caller's identity to the auth you already have.
  116. **Over HTTP**, the client's `Authorization` header and cookies are forwarded to your controller. If your app accepts API tokens, as most API apps and Devise token setups do, there is nothing to configure.
  117. **Over stdio** there is no HTTP request, so you choose who local sessions act as:
  118. ```ruby
  119. # config/initializers/mcp_on_ruby.rb
  120. McpOnRuby.configure do |config|
  121. # Devise / Warden apps: sign in as a user for each tool call (nothing is stored in the session).
  122. config.stdio_user = -> { User.find_by!(email: ENV.fetch("MCP_USER")) }
  123. # Token-authenticated apps: send headers your app already accepts.
  124. config.stdio_headers = -> { { "Authorization" => "Bearer #{ENV.fetch("MCP_TOKEN")}" } }
  125. end
  126. ```
  127. For Devise and Warden, the user is signed in with the `:user` scope (change it with `config.warden_scope`). Other apps read the stdio user with `mcp_user`.
  128. **Rails 8 authentication** (`bin/rails generate authentication`) uses neither Warden nor tokens. Teach its concern about API tokens for HTTP clients and about `mcp_user` for stdio:
  129. ```ruby
  130. # app/controllers/concerns/authentication.rb
  131. def resume_session
  132. Current.session ||= find_session_by_cookie || find_session_by_token || find_session_for_mcp
  133. end
  134. # HTTP clients send `Authorization: Bearer <api_token>` (add `has_secure_token :api_token` to User).
  135. def find_session_by_token
  136. authenticate_with_http_token do |token, _options|
  137. User.find_by(api_token: token)&.sessions&.new(user_agent: request.user_agent, ip_address: request.remote_ip)
  138. end
  139. end
  140. # `bin/rails mcp:stdio` sessions act as config.stdio_user.
  141. def find_session_for_mcp
  142. mcp_user&.sessions&.new
  143. end
  144. ```
  145. The sessions are built but never saved, so tool calls don't add rows to `sessions` or set cookies.
  146. If authentication fails, the agent gets a clear "Not authenticated (401)" tool error and nothing runs.
  147. ### Authorization
  148. There is nothing new to learn, because tool calls run your controller code. `authorize`, `policy_scope`, `can?`, `current_user.orders.find`, and `head :forbidden` behave exactly as they do for any other client. A 403 reaches the agent as "Not permitted (403)".
  149. Inside a controller, `mcp_request?` tells you whether an agent is calling, and `mcp_tool_name` tells you which tool:
  150. ```ruby
  151. before_action :require_admin, if: :mcp_request?
  152. ```
  153. ### Safety
  154. Agents act on behalf of real users, so the defaults are conservative:
  155. - **Writes are explicit.** Declaring `mcp_tool` on an action routed with `POST`, `PUT`, `PATCH`, or `DELETE` without `write: true` raises `McpOnRuby::ConfigurationError`. This happens at boot in production and when running `bin/rails mcp:doctor`.
  156. - **Honest hints.** Every tool is annotated from its HTTP verb (`readOnlyHint`, `destructiveHint`, `idempotentHint`), so clients like Claude can ask before destructive calls. Override with `annotations:`.
  157. - **A kill switch.** `config.allow_writes = false` hides and refuses every write tool, for example on a read-only replica or a demo environment.
  158. - **No accidental exposure.** Only declared actions are reachable, and declarations without a route raise. `bin/rails mcp:tools` shows exactly what is exposed.
  159. - **No leaked internals.** Server errors reach the agent as a generic error. Details go to `Rails.error` and your logs.
  160. - **Browser protection.** The endpoint rejects requests from foreign browser origins. Requests dispatched by MCP skip Rails' CSRF token check, which is safe because only the dispatcher can mark a request as MCP. Regular requests to the same actions stay protected.
  161. See [SECURITY.md](SECURITY.md) for the full threat model.
  162. ### Results and errors
  163. | Your controller returns | The agent receives |
  164. |---|---|
  165. | `2xx` with JSON | `structuredContent` plus the JSON as text |
  166. | `2xx` with plain text | The text |
  167. | `204 No Content` | A short success message |
  168. | `401` / `403` / `404` | Tool error: not authenticated / not permitted / not found |
  169. | `422` with JSON | Tool error including your validation messages, so the agent can correct itself |
  170. | Other `4xx` | Tool error with the status, plus the body when it is JSON |
  171. | `3xx` to a sign-in page | Tool error: not authenticated (Rails 8 authentication and Devise redirect unauthenticated requests) |
  172. | Other `3xx` | Tool error naming the redirect target (redirects are not followed) |
  173. | HTML | Tool error asking for JSON. Use `respond_to` with `format.json`. |
  174. | `5xx` or an exception | Generic tool error. Details are reported to `Rails.error`, never sent. |
  175. ### Tools without a controller
  176. For logic that has no endpoint, add a tool class from the official SDK. It runs alongside your controller tools:
  177. ```ruby
  178. class ReindexSearchTool < MCP::Tool
  179. description "Rebuild the search index"
  180. def self.call(server_context:)
  181. SearchIndex.rebuild!
  182. MCP::Tool::Response.new([{ type: "text", text: "Reindexed" }])
  183. end
  184. end
  185. McpOnRuby.configure { |config| config.tools = [ReindexSearchTool] }
  186. ```
  187. These tools bypass your controllers, so they also bypass your controller authentication. Use them for things that are safe for every caller.
  188. ### Observability
  189. Every tool call emits `tool_call.mcp_on_ruby` through `ActiveSupport::Notifications`:
  190. ```ruby
  191. ActiveSupport::Notifications.subscribe("tool_call.mcp_on_ruby") do |event|
  192. Rails.logger.info(
  193. "MCP #{event.payload[:tool]} → #{event.payload[:status]} " \
  194. "(#{event.payload[:transport]}, #{event.duration.round}ms)"
  195. )
  196. end
  197. ```
  198. Payload: `tool`, `controller`, `action`, `transport` (`:http` or `:stdio`), `status`, and `error`. Tool calls also show up in your normal request logs and APM traces as requests to the underlying routes.
  199. ### Connecting clients
  200. <details>
  201. <summary><b>Claude Code</b></summary>
  202. ```bash
  203. # Remote or production
  204. claude mcp add --transport http my-app https://my-app.example.com/mcp \
  205. --header "Authorization: Bearer $MY_APP_API_TOKEN"
  206. # Local, over stdio (run from your app's directory)
  207. claude mcp add my-app -e MCP_USER=alice@example.com -- bin/rails mcp:stdio
  208. ```
  209. </details>
  210. <details>
  211. <summary><b>Claude Desktop</b></summary>
  212. Claude Desktop starts servers without your shell environment, so rbenv, asdf, and mise aren't loaded. Point it at your app's Ruby directly, and use `-C` to run from the app's directory:
  213. ```bash
  214. # In your app directory, print the Ruby to use:
  215. ruby -e 'puts RbConfig.ruby'
  216. ```
  217. ```json
  218. {
  219. "mcpServers": {
  220. "my-app": {
  221. "command": "/Users/you/.rbenv/versions/3.4.7/bin/ruby",
  222. "args": ["-C", "/path/to/my-app", "bin/rails", "mcp:stdio"],
  223. "env": { "MCP_USER": "alice@example.com" }
  224. }
  225. }
  226. }
  227. ```
  228. Update `command` when you upgrade Ruby.
  229. </details>
  230. <details>
  231. <summary><b>Cursor</b></summary>
  232. `.cursor/mcp.json`:
  233. ```json
  234. {
  235. "mcpServers": {
  236. "my-app": {
  237. "url": "http://localhost:3000/mcp",
  238. "headers": { "Authorization": "Bearer YOUR_API_TOKEN" }
  239. }
  240. }
  241. }
  242. ```
  243. </details>
  244. <details>
  245. <summary><b>MCP Inspector</b></summary>
  246. ```bash
  247. # Browse and call tools in the browser
  248. npx @modelcontextprotocol/inspector bin/rails mcp:stdio
  249. # Or from the command line
  250. npx @modelcontextprotocol/inspector --cli http://localhost:3000/mcp --transport http \
  251. --header "Authorization: Bearer $MY_APP_API_TOKEN" --method tools/list
  252. ```
  253. </details>
  254. <details>
  255. <summary><b>MCP registries and gateways</b></summary>
  256. Register your `/mcp` endpoint with an MCP-compatible registry or gateway when you want discovery, access control, audit trails, and approvals managed centrally. Rails still owns the tools and enforces your app's own authorization on every call.
  257. </details>
  258. ## Testing
  259. Test tools the way agents call them: through the MCP server and your real controllers.
  260. ```ruby
  261. # spec/rails_helper.rb
  262. require "mcp_on_ruby/rspec"
  263. # test/test_helper.rb
  264. class ActiveSupport::TestCase
  265. include McpOnRuby::TestHelper
  266. end
  267. ```
  268. ```ruby
  269. it "shows agents only their own orders" do
  270. result = mcp_call :orders_index, { status: "pending" }, headers: { "Authorization" => "Bearer #{alice.api_token}" }
  271. expect(result).to be_success
  272. expect(result.structured.pluck("id")).to eq([alice_order.id])
  273. end
  274. it "stops agents from reading other users' orders" do
  275. result = mcp_call :orders_show, { id: bob_order.id }, as: alice # signs in through Devise/Warden
  276. expect(result).to be_error
  277. expect(result.status).to eq(404)
  278. end
  279. ```
  280. `mcp_call` returns a result with `success?`, `error?`, `structured` (the parsed JSON), `status` (for failures), `text` (what the agent reads), and `protocol_error` (unknown tool, invalid arguments). `mcp_tools` lists the tool names an agent sees.
  281. ## Configuration
  282. ```ruby
  283. # config/initializers/mcp_on_ruby.rb
  284. McpOnRuby.configure do |config|
  285. config.server_name = "my-app"
  286. config.instructions = "Tools for managing orders in My App. Amounts are in cents."
  287. config.stdio_user = -> { User.find_by!(email: ENV.fetch("MCP_USER")) }
  288. end
  289. ```
  290. | Option | Default | Description |
  291. |---|---|---|
  292. | `server_name` | app name, dasherized | Name reported to clients |
  293. | `server_version` | `nil` | Version reported to clients |
  294. | `instructions` | `nil` | Guidance sent to the agent when it connects |
  295. | `stdio_user` | `nil` | Callable returning the user `mcp:stdio` sessions sign in as (Devise/Warden) |
  296. | `stdio_headers` | `nil` | Callable returning headers `mcp:stdio` sessions send (token auth) |
  297. | `warden_scope` | `:user` | Warden scope used for `stdio_user` and `mcp_call(as:)` |
  298. | `allow_writes` | `true` | Set `false` to hide and refuse every `write: true` tool |
  299. | `tools` | `[]` | Extra `MCP::Tool` classes served alongside controller tools |
  300. | `allowed_origins` | `[]` | Browser origins allowed to call the endpoint, in addition to same-origin |
  301. | `max_request_bytes` | 4 MiB | Largest MCP request body accepted |
  302. | `tool_name` | `"<controller>_<action>"` | Callable `(controller_path, action)` returning default tool names |
  303. ### Commands
  304. | Command | What it does |
  305. |---|---|
  306. | `bin/rails g mcp_on_ruby:install [--path=/mcp]` | Adds the initializer and mounts the endpoint |
  307. | `bin/rails g mcp_on_ruby:expose CONTROLLER ACTION...` | Adds `mcp_tool` declarations to a controller |
  308. | `bin/rails mcp:tools` | Lists exposed tools, their routes, and their access level |
  309. | `bin/rails mcp:stdio` | Serves your tools over stdio for local agents |
  310. | `bin/rails mcp:doctor` | Checks the mount, declarations, and stdio identity; exits non-zero on errors |
  311. ## Compatibility
  312. | | Supported |
  313. |---|---|
  314. | Ruby | 3.2, 3.3, 3.4, 4.0 |
  315. | Rails | 7.1, 7.2, 8.0, 8.1 |
  316. | MCP protocol | Every version the official `mcp` gem supports, negotiated per client |
  317. | Transports | Streamable HTTP (stateless), stdio |
  318. | Controllers | `ActionController::Base` and `ActionController::API` |
  319. CI runs the full suite on every supported Ruby and Rails combination.
  320. ## When to use something else
  321. MCP on Ruby is for exposing an **existing Rails app** to agents. Other tools fit other jobs:
  322. - **[`mcp`](https://github.com/modelcontextprotocol/ruby-sdk)**, the official Ruby SDK, if you're building a standalone MCP server. MCP on Ruby runs on top of it.
  323. - **[ActionMCP](https://github.com/seuros/action_mcp)** if you're on Rails 8.1+ and prefer dedicated tool, prompt, and resource classes with a full MCP feature set.
  324. - **[Tidewave](https://tidewave.ai)** if you want coding agents to understand your codebase while you develop. MCP on Ruby is about your app's *runtime* behavior for your *users*.
  325. ## Contributing
  326. Bug reports, ideas, and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
  327. ```bash
  328. git clone https://github.com/nagstler/mcp_on_ruby && cd mcp_on_ruby
  329. bin/setup
  330. bundle exec rake # specs + RuboCop
  331. RAILS_VERSION=7.2 bundle update && bundle exec rspec # another Rails series
  332. ```
  333. Release notes are in [CHANGELOG.md](CHANGELOG.md).
  334. ## License
  335. Released under the [MIT License](LICENSE.txt).
  336. ## Acknowledgments
  337. - The [Model Context Protocol](https://modelcontextprotocol.io) team for the specification.
  338. - The maintainers of the official [Ruby SDK](https://github.com/modelcontextprotocol/ruby-sdk), on whose work this gem is built.
  339. - The Rails community, whose conventions this gem tries hard not to break.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.