Custom Tools
Build your own MCP tools that run alongside the 35 built-in ones.
NoteCustom tools have full access to your Rails environment - ActiveRecord, services, mailers, everything. They appear alongside the 35 built-in tools in both MCP and CLI.
Creating a custom tool
Custom tools are subclasses of MCP::Tool that you register in your configuration.
# app/mcp_tools/rails_get_business_metrics.rb
require "mcp" # the gem loads the MCP SDK lazily, so a file read first needs it
class RailsGetBusinessMetrics < MCP::Tool
tool_name "rails_get_business_metrics"
description "Returns key business metrics for the current environment"
input_schema(
properties: {
period: {
type: "string",
description: "Time period: day, week, month",
enum: %w[day week month]
}
}
)
def self.call(period: "week", server_context: nil)
# Your logic here - full access to Rails models, services, etc.
stats = {
users: User.where("created_at > ?", period_start(period)).count,
orders: Order.where("created_at > ?", period_start(period)).count,
revenue: Order.where("created_at > ?", period_start(period)).sum(:total)
}
MCP::Tool::Response.new([
{ type: "text", text: format_stats(stats) }
])
end
def self.period_start(period)
case period
when "day" then 1.day.ago
when "week" then 1.week.ago
when "month" then 1.month.ago
end
end
def self.format_stats(stats)
<<~TEXT
## Business Metrics
- New users: #{stats[:users]}
- New orders: #{stats[:orders]}
- Revenue: $#{stats[:revenue]}
TEXT
end
end
Registering custom tools
Add your tool classes to the configuration:
# config/initializers/rails_ai_context.rb
if defined?(RailsAiContext) && RailsAiContext.respond_to?(:configure)
RailsAiContext.configure do |config|
config.custom_tools = ["RailsGetBusinessMetrics"]
end
end
Custom tools appear alongside built-in tools in the MCP server and CLI, and in the tool counts of the generated context files. In CLI mode the root file's list of commands names them too; in MCP mode the client lists them with their descriptions.
Use the class name as a string: classes under app/ (including
app/mcp_tools/) are not autoloadable while initializers run, so a bare
constant reference there aborts boot with a NameError. String entries are
resolved after the app finishes booting. A bare constant still works for
classes already loaded when the initializer runs (e.g. defined in lib/
and required manually).
Using BaseTool features
For access to caching, pagination, and helper methods, you can use RailsAiContext::Tools::BaseTool utilities directly:
class RailsGetDeployStatus < MCP::Tool
tool_name "rails_get_deploy_status"
description "Returns current deployment status"
def self.call(server_context: nil)
# Use SafeFile for safe reading
version = RailsAiContext::SafeFile.read(Rails.root.join("REVISION"))
deployed_at = File.mtime(Rails.root.join("tmp/restart.txt")) rescue nil
MCP::Tool::Response.new([
{ type: "text", text: "Version: #{version&.strip}\nDeployed: #{deployed_at}" }
])
end
end
Naming conventions
- Prefix tool names with
rails_per MCP best practices - Use
rails_get_for data retrieval tools - Use
rails_withoutget_for action tools (e.g.,rails_validate)
Testing custom tools
Use the built-in TestHelper module.
With the gem in group: :development, the initializer's guard makes
config.custom_tools a no-op in the test environment, so name-based lookup
(execute_tool("rails_get_business_metrics")) won't find custom tools
there. Either install the gem with group: %i[development test], or pass
the class itself: execute_tool(RailsGetBusinessMetrics). Built-in tools
resolve by name in any environment.
With RSpec
# spec/mcp_tools/rails_get_business_metrics_spec.rb
require "rails_helper"
require "rails_ai_context/test_helper"
RSpec.describe RailsGetBusinessMetrics do
include RailsAiContext::TestHelper
it "is registered as an MCP tool" do
assert_tool_findable("rails_get_business_metrics")
end
it "returns metrics for the default period" do
response = execute_tool("rails_get_business_metrics")
assert_tool_response_includes(response, "Business Metrics")
end
it "accepts a period parameter" do
response = execute_tool("rails_get_business_metrics", period: "month")
assert_tool_response_includes(response, "Revenue")
end
it "does not expose sensitive data" do
response = execute_tool("rails_get_business_metrics")
assert_tool_response_excludes(response, "password")
end
end
With Minitest
# test/mcp_tools/rails_get_business_metrics_test.rb
require "test_helper"
require "rails_ai_context/test_helper"
class RailsGetBusinessMetricsTest < ActiveSupport::TestCase
include RailsAiContext::TestHelper
test "is registered as an MCP tool" do
assert_tool_findable("rails_get_business_metrics")
end
test "returns metrics" do
response = execute_tool("rails_get_business_metrics")
assert_tool_response_includes(response, "Business Metrics")
end
end
TestHelper API
| Method | Description |
|---|---|
execute_tool(name_or_class, **args) |
Execute a tool by name, short name, or class. Returns MCP::Tool::Response, and raises with the tool's text when it returns an error. |
execute_tool_with_error(name_or_class, **args) |
Execute a tool expecting an error response. Returns it, and fails the test when the call succeeds. |
assert_tool_findable(name_or_class) |
Assert the tool is registered and discoverable. |
assert_tool_response_includes(response, text) |
Assert response contains the given text. |
assert_tool_response_excludes(response, text) |
Assert response does NOT contain the given text. |
extract_response_text(response) |
Extract plain text from an MCP::Tool::Response. |
Name resolution is fuzzy - all of these resolve to the same tool:
execute_tool("rails_get_schema")
execute_tool("get_schema")
execute_tool("schema")
execute_tool(RailsAiContext::Tools::GetSchema)
Excluding built-in tools
If a custom tool replaces a built-in one, exclude the original:
RailsAiContext.configure do |config|
config.custom_tools = ["MyBetterSecurityScan"]
config.skip_tools = %w[rails_security_scan]
end
The replacement is listed with the app's tools. The gem's own hints, the guide's steps and rails_get_context leave it out, since they would call it with the built-in's arguments.
A custom rails_get_config listed in skip_tools replaces the built-in with its sections: the old names such as rails_get_gems then reach nothing, and no answer points at a section.
A custom tool may also reuse one of those old names with the built-in left on. It is served as its own tool. The gem's own hints still mean the built-in section and print it as rails_get_config(section:"gems").
Tips
- Custom tools have access to the full Rails environment - ActiveRecord, services, mailers, etc.
- Keep tools read-only when possible. MCP tools annotated as non-destructive build more trust with AI clients.
- Return
MCP::Tool::Responseobjects withtype: "text"content blocks. - A response you build with
MCP::Tool::Response.newis sent as written. Theconfig.max_tool_response_charscap (default: 200,000) is applied by the built-in tools'text_response, so keep a custom tool's output short yourself. - Through the mounted engine a call's answer is sent whole when the call is over. Progress and log notifications a tool sends (
server_context.report_progress,server_context.notify_log_message) arrive together with its answer, and a request it makes of the client (sampling, elicitation, roots) fails at once, saying why. stdio and the standalone HTTP server deliver both as they are sent.