I’ve been building Rails applications for more than a decade, and I’ve watched the AI hype cycle go from “neat demo” to “potential productivity multiplier” to “actual production feature.” If you’re a senior consultant or a lead architect right now, you’re likely fielding questions from stakeholders about how to integrate AI into existing Rails monoliths without turning your codebase into a maintenance nightmare. The temptation is to reach for the shiniest new framework, but if you want production-grade intelligence, you need to look beyond the hype and understand what actually works at scale. Good rails ai engineering means treating the LLM as one more dependency behind well-tested service objects, not as the center of your architecture.
The current landscape of open-source agent frameworks is crowded. LangChain has become something of a default, but it’s often too generic, requiring significant plumbing to make it feel like a native part of a Rails app. Then there’s LlamaIndex, which excels at data ingestion but can feel abstract when you’re trying to wire it into Active Record. What’s interesting right now is the emergence of Ruby-specific SDKs and frameworks that aim to bridge the gap between the agentic world and the object-oriented Rails paradigm. I’m seeing tools that allow you to define agents as Ruby objects, leveraging the language’s introspection capabilities rather than fighting against JSON schemas and YAML configs.
Integrating AI Agents with the Rails SDK
The most pragmatic approach I’ve seen recently involves using the official Ruby SDK for the Model Context Protocol. If you’d rather expose your own app to agents, I cover the server side in building a Rails MCP server. This approach moves away from the “wrapper” mentality and instead gives you first-class access to the underlying protocols that agents use to reason, plan, and execute. When you’re building production-grade intelligence, you don’t want a black box; you want observability, you want retry logic, and you want to be able to debug the agent’s thought process the same way you would debug a complex SQL query.
Consider the setup for a typical Rails integration. The SDK ships as the mcp gem and follows the Model Context Protocol (MCP) specification, so your app can talk to any MCP-compatible server, not just one vendor’s. Its HTTP client also needs faraday, plus event_stream_parser for servers that stream responses:
# Gemfile
gem "mcp"
gem "faraday", ">= 2.0"
gem "event_stream_parser", ">= 1.0"I keep the client in a small service object rather than an initializer, so each call opens and closes its own connection:
# app/services/agent_tools.rb
class AgentTools
def initialize(url: ENV.fetch("MCP_SERVER_URL"))
@transport = MCP::Client::HTTP.new(url: url)
@client = MCP::Client.new(transport: @transport)
end
def call(tool_name, **arguments)
@client.connect
tool = @client.tools.find { |t| t.name == tool_name }
raise ArgumentError, "Unknown MCP tool: #{tool_name}" unless tool
@client.call_tool(tool: tool, arguments: arguments)
ensure
@transport.close
end
end
AgentTools.new.call("lookup_order", order_id: "42")I ran this with mcp 1.11.0 against a local MCP server exposing one lookup_order tool, and it returned the tool’s result as a JSON-RPC response. Because it’s a plain Ruby object, you can call it from a controller, a background job or a scheduled task. In practice, put it in an Active Job: tool calls go over the network and can take seconds, which you don’t want inside a web request.
From Prototypes to Production: The Skill Gap
Having the SDK installed is the easy part. The real work—and where most teams fail—is in defining the “skills” or “tools” that your agent is allowed to use. In an agentic system, a tool is essentially a function that the Large Language Model (LLM) can call to get more information or perform an action. If you’re building a Rails app that needs to, say, query a database, send an email, or call an external API, you need to expose those capabilities to the agent in a controlled way.
I’ve seen projects where developers simply dump all their API endpoints into the agent’s context and hope for the best. This is a recipe for disaster in production. You need a “skills registry.” This is where you explicitly define what the agent is allowed to do. For a Rails app, this often means creating thin wrapper services around your existing business logic.
For example, imagine you want an agent to help users manage their subscriptions. Instead of letting the agent loose on your Stripe integration, you create a SubscriptionManagementService. The agent then calls this service via a defined interface. This keeps your business logic testable and your AI interactions predictable.
# app/services/subscription_management_service.rb
class SubscriptionManagementService
def self.cancel(user_id, subscription_id)
# Business logic, validation, auditing
subscription = User.find(user_id).subscriptions.find(subscription_id)
subscription.cancel!
# Return a structured result the agent can parse
{ status: "success", message: "Subscription cancelled" }
rescue => e
{ status: "error", message: e.message }
end
endThen, in your agent configuration, you map a natural language intent to this service method. This “skills-based” approach is what separates a toy demo from a production system. It forces you to think about idempotency, error handling, and data validation—all the things that make Rails robust—before you even bring an LLM into the loop.
Measure Latency Before You Commit
Latency depends far more on your LLM provider, the number of tool calls per task and your network than on which Ruby library you pick. Build a small prototype for one real task, log how long each tool call and model response takes, and use those numbers to decide whether the feature belongs in a request or in a background job.
Managing Context and Memory
One of the hardest parts of building AI-enhanced Rails apps is managing context. LLMs have a limited token window, and Rails apps often deal with rich data models. If you try to dump an entire User record and all their associated orders into every prompt, you’ll hit token limits quickly, and you’ll also pay for tokens you don’t need.
The skill here is “summarization” and “selective context.” You want to train your agents (or write the code that feeds them) to only send the relevant data. This might mean querying the database for the specific IDs needed, or using a Rails serializer to generate a compact JSON payload that highlights only the fields the agent cares about.
Furthermore, consider the concept of “short-term memory” versus “long-term memory.” In a web application context, you often want stateless interactions or session-based memory. You can store the conversation history in a database table—perhaps using a conversations table that stores the raw tool calls and LLM responses. This allows you to rebuild context if a user refreshes the page or if you need to audit what the agent did during a specific session.
From an architectural standpoint, I advocate for a “tool-first” mentality. Don’t let the LLM decide how to do something if you can code it. Let the LLM decide what needs to be done, and then have your Rails code execute it. This gives you the best of both worlds: the natural language understanding of the AI and the reliability of tested Ruby code.
Security Considerations in the Age of Agents
Security is the area where I see the most danger for Rails teams jumping on the AI bandwagon. When you give an agent access to tools, you are effectively giving it access to your system’s capabilities. If an agent can call a “delete_user” tool, and the prompt engineering isn’t perfect, you might find yourself with a security vulnerability.
The production-grade approach is to treat every agent tool call as a privileged API request. You should implement strict authorization checks inside every service method that an agent can call. Just because the agent wants to run a query doesn’t mean it should.
I recommend using your existing Rails authorization library (like Pundit or CanCanCan) inside your service objects. If the agent calls a tool, your service object checks: “Does the current user have permission to perform this action?” If not, return a structured error. This integrates seamlessly with your existing auth flow and doesn’t require you to learn a new security model from scratch.
Also, be wary of prompt injection. Since agents often take user input and inject it into prompts, you need sanitization strategies. Treat user input as untrusted data. If an agent is about to execute a tool based on user text, ensure that text is validated and escaped appropriately. The Rails community is good at this; apply your existing security habits to the AI layer.
Observability: Knowing What Your Agent Is Doing
In a traditional Rails app, you have logs, metrics, and maybe New Relic. With AI agents, you need a new layer of observability. You need to know: What tools did the agent call? Did they succeed or fail? What was the LLM’s reasoning for choosing that tool?
I suggest implementing a simple “agent log” table in your database. Every time the agent invokes a tool, record the tool name, the arguments passed, the result, and the timestamp. This data is gold for debugging. If a user reports “the AI messed up my order,” you can look at the logs, see which tool was called, and understand the context.
You can also use this data for improvement. By analyzing the logs, you might discover that your agent is calling a specific tool 90% of the time, but it’s failing 50% of the time. That’s a signal that your tool’s interface needs refinement, or that the LLM needs better prompting for that specific task. This feedback loop is essential for moving from “experimental” to “production-grade.” To turn those logs into repeatable checks, see LLM evals for Rails.
Frequently asked questions
Do I need Python to add AI features to a Rails app?
No. Most LLM providers expose HTTP APIs with Ruby clients, and MCP has an official Ruby SDK. Keep the AI calls in service objects and background jobs inside your Rails app.
Where should agent tool logic live in Rails?
In plain service objects that wrap your existing business logic. The agent calls the service; the service handles validation, authorization and auditing, so the same rules apply whether a person or an agent triggers the action.
How do I keep an AI agent from doing something it shouldn’t?
Expose only the tools it needs, run your normal authorization checks (Pundit, CanCanCan) inside every tool, treat user text as untrusted input, and log every tool call so you can audit it.
Conclusion: Building the Skill, Not Just the Feature
Integrating AI into Rails is not about finding the perfect gem and dropping it in. It’s about developing a new set of engineering skills. You need to think about your app not just as Ruby code, but as a system that can be reasoned about by an LLM. This requires disciplined tool design, rigorous security checks, and a commitment to observability.
The frameworks and SDKs available today—particularly those offering official Ruby support—provide the plumbing. But the production-grade result comes from how you wire that plumbing into your existing Rails architecture. By treating agents as consumers of well-defined services, and by applying the same testing and security practices you use for any other feature, you can add genuine intelligence to your applications without sacrificing the maintainability that makes Rails great.
If you’re starting down this path, my honest advice is to start small. Pick one tedious task—like generating email responses to support tickets or summarizing long articles—and build a thin wrapper around it. Get comfortable with the flow of user input -> agent tool call -> service execution -> response generation. Once you have that pattern locked down, scaling up to more complex agentic workflows becomes a matter of infrastructure, not a rewrite of your entire codebase.
If you want help with that first feature, I build and review AI features for existing Rails apps through my AI software development service. Book a discovery call to scope it.


