A Rails MCP server is a Rails endpoint that speaks the Model Context Protocol (MCP), so AI clients such as coding assistants and chat apps can call your app’s functions as tools. With the official Ruby SDK, the mcp gem, you write each tool as a small Ruby class and expose them through one controller action.
This guide shows how to build that server: a tool class, an authenticated stateless HTTP endpoint, a way to test it with curl, and the security decisions that matter once a model can act on your data. If you want the wider picture first, read my guide to Ruby on Rails AI integration with RubyLLM. That article covers calling a model from Rails. MCP is the other direction: letting a model call into Rails.
I ran the Ruby code and the
curlcalls in this article againstmcp1.9.0 on Rails 8.1.4.1 and Ruby 3.3.6, in a throwaway API-only app with SQLite. I did not run themountvariant, theallowed_hostssettings or the OAuth options on a live deployment. Those parts follow the SDK documentation, and I say so where it matters. I also did not connect a real AI client, so check your client’s own docs for its MCP configuration.
What MCP is and why Rails teams care
MCP is an open protocol that standardizes how an AI application discovers and calls external capabilities. A server publishes tools (functions with a JSON Schema for their inputs), and optionally resources and prompts. A client lists the tools and the model decides when to call them. Messages are JSON-RPC 2.0.
The practical value is reuse. Before MCP, every assistant needed its own integration with your app. With one MCP endpoint, any compliant client can use the same tools. For a SaaS product that can mean an internal support assistant that looks up an account, or a developer tool that queries staging data.
Treat that power with care. A tool is an API that a language model can call with arguments you did not write. Everything you know about securing an API applies, with one addition: the caller can be tricked by text in the data it reads. I come back to this in the security section.
Why now: the official SDK is moving fast
As of November 7, 2026, the latest mcp gem on RubyGems is version 1.9.0, released on November 3, 2026. RubyGems lists more than 12.8 million downloads for it. The repository is modelcontextprotocol/ruby-sdk, under the same GitHub organization as the protocol itself. It lists server and client support and a Rails integration. The README says new contributions are under Apache 2.0, with existing code under MIT.
Ruby had MCP libraries before this. fast-mcp (MIT) is a popular community option with its own Rails initializer and generator. I use the official SDK here because it lives under the protocol’s own GitHub organization, which makes it a safe default for a new project. Both are reasonable choices, and I compare them below.
How the pieces fit together
A request to your server goes through four steps:
- The client sends a JSON-RPC message over HTTP to one URL, for example
POST /mcp. - Your Rails code authenticates the request. Your own code does this, not the SDK.
- You build an
MCP::Serverwith the tool classes this caller may use. - The SDK’s transport parses the message, runs
initialize,tools/listortools/call, and returns a JSON-RPC response.
The transport for HTTP is called Streamable HTTP. The SDK ships it as MCP::Server::Transports::StreamableHTTPTransport. For local tools you can use a stdio transport instead, where the client starts your process and talks over stdin and stdout. A hosted Rails app needs HTTP.
Install the gem
bundle add mcpI used an API-only app to keep the demo small, but the code works the same in a full Rails app.
rails new demo --api --minimal
cd demo
bundle add mcp
bin/rails g model Project name:string status:string
bin/rails db:migrateWrite your first tool
A tool is a subclass of MCP::Tool. It declares a description, a JSON Schema for its input, and a class method call that returns an MCP::Tool::Response. Because Rails autoloads app/, a new folder app/tools works with no configuration.
# app/tools/list_projects_tool.rb
class ListProjectsTool < MCP::Tool
tool_name "list_projects"
description "List projects, optionally filtered by status"
input_schema(
properties: {
status: { type: "string", enum: %w[active archived] },
limit: { type: "integer", minimum: 1, maximum: 50 }
}
)
annotations(read_only_hint: true, destructive_hint: false)
def self.call(status: nil, limit: 10, server_context:)
scope = Project.order(:name)
scope = scope.where(status: status) if status
names = scope.limit(limit).pluck(:name)
MCP::Tool::Response.new([{ type: "text", text: names.join("\n") }])
end
endA few details are worth knowing:
- The tool name. Without
tool_name, the SDK derives the name from the class. In my run,ListProjectsToolwas published aslist_projects_tool. I set an explicit name so a class rename does not silently change the public name that clients and prompts depend on. - The schema is the contract. The SDK validates arguments against
input_schemabeforecallruns. When I sentstatus: "bogus", the server returned a result withisError: trueand the messageInvalid arguments: value at /status is not one of: ["active", "archived"]. The model sees that error and can correct itself. Useenum,minimumandmaximumto keep inputs narrow. - Annotations are hints.
read_only_hinttells a client the tool does not change data. Clients can use that to decide whether to ask the user for confirmation. It is not enforcement, so a tool that writes data must still check permissions itself. server_contextis how you pass the caller’s identity into a tool. It is the same hash you give toMCP::Server.new. Keep it small and put the current user or tenant in it.
Return small, useful text. A tool that dumps 10,000 rows wastes the model’s context and money. Paginate, summarize and cap limit.
Add an authenticated endpoint
The SDK docs describe two ways to serve HTTP from Rails: mount the transport as a Rack app in config/routes.rb, or call it from a controller. I prefer the controller for a SaaS app, because the request is a normal Rails request: you get your authentication code, logging, error reporting and rate limiting.
# app/controllers/mcp_controller.rb
class McpController < ActionController::API
before_action :authenticate!
def handle
server = MCP::Server.new(
name: "railsdev_demo",
version: "1.0.0",
tools: [ListProjectsTool],
server_context: { token: @token }
)
transport = MCP::Server::Transports::StreamableHTTPTransport.new(
server, stateless: true, serve_subscriptions_listen: false
)
status, headers, body = transport.handle_request(request)
render json: body.first, status: status, headers: headers
end
private
def authenticate!
@token = request.authorization.to_s.delete_prefix("Bearer ")
expected = ENV.fetch("MCP_TOKEN")
head :unauthorized unless ActiveSupport::SecurityUtils.secure_compare(@token, expected)
end
end# config/routes.rb
post "/mcp", to: "mcp#handle"Three choices in this controller come from the SDK documentation:
- A new server per request. This lets you vary the tool list per caller. A read-only API key can get only read tools. The docs describe this as the point of the controller approach.
stateless: true. The server issues no session ID and keeps no session in memory, so it works behind several app servers with no sticky sessions. The cost, per the docs, is that features needing a persistent channel, such as progress notifications and server-to-client requests, are unavailable. Most tool-only servers do not need them.serve_subscriptions_listen: false. A controller’srenderbuffers the whole response, so it cannot hold open a streaming connection. The docs tell you to turn this off in the controller pattern, and to use the mount approach if you need those streams.
The example compares a static token. In a real app, look up an API key or OAuth access token, load the user it belongs to, and put that user in server_context. Do not use one shared secret for all callers in production.
Test it with curl
You do not need an AI client to test a server. Start bin/rails s and send the protocol messages yourself. Streamable HTTP clients send an Accept header that lists both application/json and text/event-stream.
curl -s -X POST localhost:3000/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'Authorization: Bearer dev-secret' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'In my run, initialize returned the server name, version and capabilities, and tools/list returned the tool with its schema and annotations. This call returned the project names:
curl -s -X POST localhost:3000/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'Authorization: Bearer dev-secret' \
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_projects","arguments":{"status":"active"}}}'{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"Alpha"}],"isError":false}}A request with no token returned HTTP 401, from the before_action. That is the behavior you want to write a request spec for. For the first tests, I suggest three: an unauthenticated call is rejected, an invalid argument returns isError: true, and a caller without permission never sees the tool in tools/list.
Security: what changes when the caller is a model
Authentication is the start, not the end. These are the points I check before an MCP endpoint goes live.
- Authorize inside every tool. Scope queries through the current user, for example
current_user.projects, neverProject.all. The model can send any argument the schema allows. - Prefer read-only tools first. Add tools that write data one at a time, with narrow schemas, and log every call with the user and the arguments.
- Treat tool output as untrusted input to the model. If a tool returns user-written text, such as a support ticket, that text can contain instructions aimed at the model. Do not give one assistant both access to private data and a tool that can send it out, such as email or webhooks, without a human confirmation step. This is called prompt injection, and no schema stops it.
- Validate
HostandOrigin. The SDK documents DNS rebinding protection: the transport checks these headers by default and allows loopback hosts. On a public domain you widen the lists withallowed_hosts:andallowed_origins:. I did not test that behind a proxy, so verify it in staging. - Set size limits. The docs list
max_request_byteswith a default of 4 MiB. Lower it if your tools take small inputs. - Bind sessions to users if you are not stateless. The docs say the transport does not bind sessions to users on its own unless you give it a
session_request_validatoror token verification. That is your responsibility. - For remote clients that sign in as users, use OAuth. The SDK documentation says servers can act as OAuth 2.1 resource servers. I did not implement it for this article, so read the SDK’s authorization pages before you build it.
Never connect an MCP server that can modify production data to your development assistant with a production credential. Use a staging database and a scoped token.
Official SDK or fast-mcp?
Official mcp gem |
fast-mcp | |
|---|---|---|
| Maintainer | MCP project organization | Community (single repository) |
| Licence | Apache 2.0 for new work, MIT for existing code | MIT |
| Rails style | Plain classes, you wire the controller or mount | Initializer, generator and ActionTool::Base classes |
| Auth | You write it, or use the SDK’s token verification | Built-in token option and authenticated Rack middleware |
| Best for | New servers where you want explicit control | A quick start with Rails-flavored conventions |
I did not benchmark either, and I did not run fast-mcp for this article. The table reflects each project’s own README on November 7, 2026. If you already use fast-mcp and it works, there is no urgent reason to move.
Production checklist
- Every tool authorizes against the current user or tenant, and a request spec proves it.
- Tool inputs are narrow:
enum,maximum, required fields. - Output size is capped, and large results are paginated.
-
allowed_hostsandallowed_originsare set for your domain and tested behind your proxy. - Calls are logged with the user, tool name and arguments, and secrets are filtered.
- Rate limits protect the endpoint. Rails 8 ships
rate_limitfor controllers. - Write tools need a confirmation step in the client or a human approval path.
- The endpoint is behind HTTPS only.
When not to build an MCP server
MCP is a good fit when several AI clients need the same capabilities, or when you want users to bring their own assistant. It is more than you need if your app calls one model for one feature. In that case, calling the model API with tool calling inside your own code, as in my RubyLLM guide, is simpler and keeps everything in one place. If your assistant needs your own documents rather than live actions, start with search instead. My pgvector guide for Rails covers that.
If you want a second opinion on which approach fits your product, I help teams add AI features to existing Rails apps, including tool design and access control. See AI software development for Rails apps.
For the broader pattern, see Agent Skills for Rails.
Conclusion
An MCP server in Rails is less work than it sounds: one tool class, one controller action and one route got me a working, authenticated endpoint, and the schema validation did useful work with no extra code. The hard part is the same as for any API: deciding who may call what, and keeping the model’s inputs and outputs under control.
My recommendation: start with a stateless controller, two or three read-only tools, per-user authorization and request specs. Add write tools and OAuth only after you have logs showing how clients use the first version.
I build AI features into existing Rails apps: tool-calling endpoints with scoped access, retrieval over your own data, and tests so you know it behaves before customers see it. If you’re deciding what to expose to AI clients first, send me a short brief and book a discovery call.
Frequently asked questions
What is an MCP server in Rails?
It is a Rails endpoint that implements the Model Context Protocol, so AI clients can list and call tools your app defines. The tools are Ruby classes, and the endpoint is a normal controller or a mounted Rack app.
Which gem should I use for a Rails MCP server?
The official mcp gem is a good default for new work, and fast-mcp is a mature community alternative with Rails conventions. Check each project’s recent releases and documentation before you commit.
Does the MCP Ruby SDK work with Rails?
Yes. The SDK documents two Rails setups, a mounted transport and a controller. I ran the controller version on Rails 8.1.4.1 and Ruby 3.3.6.
Should my Rails MCP server be stateless?
For tool-only servers behind several app servers, yes. Stateless mode needs no sticky sessions. You give up features that need a persistent connection, such as progress notifications and requests from the server to the client.
How do I secure an MCP endpoint?
Authenticate every request, authorize inside every tool, keep schemas narrow, set Host and Origin allow lists, cap request and response sizes, and log calls. Do not mix private data access with a tool that can send data out unless a human confirms it.
Can I test an MCP server without an AI client?
Yes. MCP messages are JSON-RPC over HTTP, so curl works for initialize, tools/list and tools/call. Add request specs for authentication, validation and authorization.
Is MCP the same as function calling?
No. Function calling is a feature of a model API where you pass tool definitions with each request. MCP is a protocol that lets many clients discover and call the same tools from a server, so you write the tool once.


