PluginBench
MCP Server
Active
MIT

Rails AI Context MCP Server

io.github.crisnahine/rails-ai-context

45 MCP tools give AI agents live Rails schema, routes, models, and conventions—no guessing.

RepositoryRegistry
How to choose

What this kind of tool is for

  • Automate a build, test, or deployment step you repeat by hand.
  • Review or refactor code in an existing repository without leaving your agent.
  • Bridge an internal service or CLI into the agent toolset.

How to compare servers like this

Scope of control:
Repos and CI are hard to undo; prefer tools that ask before anything irreversible.
Environment fit:
Match the runtime it expects (Node, Python, a container) to what you actually run.
Maintenance signal:
Check the last-commit date — dev tooling that lags upstream breaks first.
Config surface:
Prefer tools whose environment-variable or config keys are documented plainly.

This page carries your copy-paste config: pick your MCP client in the install section on this page and use the copy button.

What is the Rails AI Context MCP server?

The Rails AI Context MCP server exposes 45 tools that give AI agents direct access to your Rails app's live schema, models, routes, controllers, views, and conventions via the Model Context Protocol. Instead of guessing, AI queries your actual codebase—associations, validations, filters, strong params, test patterns, and more—each result tagged with confidence levels so AI knows what's verified ground truth.

Rails AI Context eliminates the correction loop by replacing AI guesses with verified facts from your app. It provides 45 read-only tools that introspect your Rails schema, models, routes, controllers, views, jobs, and conventions on demand. Use it as an MCP server (stdio or HTTP), CLI commands, or static context files. Every tool returns data verified against your actual app, with confidence tags ([VERIFIED] or [INFERRED]) so AI knows what's safe to use directly versus what needs runtime checking.

How to install Rails AI Context

Copy-paste configuration for popular MCP clients.

transport: stdio
Config generated by PluginBench — verify against the source before use.
~/Library/Application Support/Claude/claude_desktop_config.json
JSON config
{
  "mcpServers": {
    "rails-ai-context": {
      "command": "https://github.com/crisnahine/rails-ai-context/releases/download/v5.30.1/rails-ai-context-mcp.mcpb",
      "args": []
    }
  }
}

Tools & capabilities

Tools this server exposes to the agent.

  • search_code — Trace method definitions, source code, callers, and tests across the codebase with filtering by type
  • get_schema — Return table columns with indexed/unique/encrypted/default hints
  • get_model_details — AST-parsed associations, validations, scopes, enums, macros with [VERIFIED]/[INFERRED] tags
  • get_callbacks — Model callbacks in Rails execution order with source code
  • get_concern — Concern methods, source, and which models include it
  • get_controllers — Controller actions with inherited filters, render map, and strong params
  • get_routes — Route helpers and required parameters
  • get_view — View templates with instance variables, Turbo wiring, Stimulus refs, and partial locals
  • get_stimulus — Stimulus controller HTML data-attributes (with dashes), targets, values, and actions
  • get_partial_interface — Partial locals and methods called on them
  • get_turbo_map — Turbo broadcast-to-subscription wiring with mismatch warnings
  • get_frontend_stack — Detect React/Vue/Svelte/Angular, Hotwire, TypeScript, package manager
  • get_test_info — Fixtures, relationships, and test template matching your patterns
  • generate_test — Test scaffolding matching your project's patterns
  • validate — Syntax, semantic, and Brakeman security checks in one call
  • security_scan — Brakeman static analysis for SQL injection, XSS, mass assignment
  • performance_check — N+1 risks, missing indexes, counter_cache, eager load candidates
  • get_conventions — Auth checks, flash messages, create action template, test patterns
  • get_config — Database, auth framework, assets, cache, queue, Action Cable configuration
  • get_gems — Notable gems with versions, categories, config file locations

Use cases

  • Prevent AI from writing duplicate migrations by checking live schema before generating code
  • Resolve correct association names and model relationships without guessing (e.g., user.articles vs user.posts)
  • Match test patterns and fixtures to your project instead of AI inventing FactoryBot when you use fixtures
  • Trace method usage across the codebase to understand impact before refactoring
  • Verify inherited before_action filters and strong params in controllers to avoid auth and validation failures

Rails AI Context MCP server FAQ

What is Rails AI Context?

Rails AI Context is an MCP server that gives AI agents (Claude, Cursor, GitHub Copilot) direct access to your Rails app's live schema, models, routes, controllers, views, and conventions. Instead of guessing, AI queries verified facts about your codebase.

Is it free?

Yes. Rails AI Context is open-source (MIT license) and available as a gem on RubyGems and as a compiled MCP binary.

How do I install it in Cursor or Claude?

Install the gem (`gem 'rails-ai-context'` in your Gemfile or `gem install rails-ai-context`), run `rails generate rails_ai_context:install` or `rails-ai-context init`, then start the server with `rails ai:serve` or `rails-ai-context serve`. Add the MCP server config to Cursor's or Claude's settings. Alternatively, download the precompiled `.mcpb` binary from releases.

Does it require authentication?

No. Rails AI Context is read-only and runs locally on your machine or within your Rails app. It does not send data to external services.

What does it cost in tokens?

Each tool call is a single request. The README shows examples like `rails_get_schema(table: users)` that return structured data—typically 100–500 tokens per call depending on your app size. This replaces 4–5 sequential file reads that would cost more tokens and introduce hallucination risk.

Can I use it without MCP?

Yes. You can use the same 38 tools via CLI commands (`rails 'ai:tool[search_code]' pattern=...`) or read static context files (CLAUDE.md, .cursor/rules, .cursorrules) that the gem generates.

README (reference)

Source of truth, from the repository.

<div align="center">

rails-ai-context

Your AI is guessing your Rails app. Every guess costs you time.

<a href="https://claude.ai/claude-code"><img src="https://img.shields.io/badge/Claude_Code-ee8b4a?style=for-the-badge&logo=anthropic&logoColor=white" alt="Claude Code"></a> <a href="https://cursor.com"><img src="https://img.shields.io/badge/Cursor-000000?style=for-the-badge&logo=cursor&logoColor=white" alt="Cursor"></a> <a href="https://github.com/features/copilot"><img src="https://img.shields.io/badge/GitHub_Copilot-000000?style=for-the-badge&logo=githubcopilot&logoColor=white" alt="GitHub Copilot"></a> <a href="https://opencode.ai"><img src="https://img.shields.io/badge/OpenCode-4285F4?style=for-the-badge&logoColor=white" alt="OpenCode"></a> <a href="https://codex.openai.com"><img src="https://img.shields.io/badge/Codex_CLI-412991?style=for-the-badge&logo=openai&logoColor=white" alt="Codex CLI"></a> <a href="docs/CLI.md"><img src="https://img.shields.io/badge/Any_Terminal-4EAA25?style=for-the-badge&logo=gnubash&logoColor=white" alt="Any Terminal"></a>

Gem Version Downloads CI MCP Registry <br> Ruby Rails Tests License: MIT

</div>

The problem

You've seen it. Your AI:

  • Writes a migration for a column that already exists - didn't check the schema
  • Creates a method that duplicates one in a concern - didn't know it was there
  • Uses the wrong association name - user.posts when it's user.articles
  • Generates tests that don't match your patterns - factories when you use fixtures, or the reverse
  • Adds a gem you already have - or calls an API from one you don't
  • Misses before_action filters from parent controllers - then wonders why auth fails
  • Invents a method that isn't in your codebase - then you spend 10 minutes finding out

You catch it. You fix it. You re-prompt. It breaks something else.

The real cost of AI coding isn't the tokens - it's the correction loop. Every guess is a round-trip: you catch it, you fix it, you re-prompt, and something adjacent breaks. This gem kills the guessing at its source.

<br>

Two commands. Problem gone.

gem "rails-ai-context", group: :development
rails generate rails_ai_context:install

Or standalone - no Gemfile needed

gem install rails-ai-context
cd your-rails-app
rails-ai-context init     # interactive setup
rails-ai-context serve    # start MCP server
<div align="center">

Install demo

</div>

Now your AI doesn't guess - it asks your app directly. 38 tools and 5 resource templates that query your schema, models, routes, controllers, views, and conventions on demand. Model introspection uses Prism AST parsing - every result carries a [VERIFIED] or [INFERRED] confidence tag so AI knows what's ground truth and what needs runtime checking.

<br>

See the difference

<div align="center">

Trace demo

</div>

One call returns: definition + source code + every caller grouped by type + tests. Replaces 4-5 sequential file reads.

<br>

What stops being wrong

Real scenarios where AI goes sideways - and what it does instead with ground truth:

You ask AI to...Without - AI guessesWith - AI verifies first
Add a subscription_tier column to usersWrites the migration, duplicates an existing columnReads live schema, spots subscription_status already exists, asks before migrating
Call user.posts in a controllerUses the guess; runtime NoMethodErrorResolves the actual association (user.articles) from the model
Write tests for a new modelScaffolds with FactoryBotDetects your fixture-based suite and matches it
Fix a failing create actionMisses inherited before_action :authenticate_user!Returns parent-controller filters inline with the action source
Build a dashboard pageInvents Tailwind classes from memoryReturns your actual button/card/alert patterns, copy-paste ready
Trace where publishable? is usedReads 6 files sequentially, still misses callersSingle call: definition + source + every caller + tests
<details> <summary><strong>Verify it on your own app</strong></summary> <br>

Run these before and after installing to see what changes in your codebase:

# Schema: does AI know what columns exist?
rails 'ai:tool[schema]' table=users

# Trace: find every caller of a method across the codebase
rails 'ai:tool[search_code]' pattern=your_method match_type=trace

# Model: associations, scopes, callbacks, concerns - all resolved
rails 'ai:tool[model_details]' model=User

# Controllers: action source + inherited filters + strong params in one shot
rails 'ai:tool[controllers]' controller=UsersController action=create

Compare what AI outputs with and without these tools wired in. The difference is measured in corrections avoided, not bytes saved.

</details> <br>

Three ways to use it

<table> <tr> <td width="33%">

MCP Server (stdio)

AI calls tools directly via the protocol. Each AI tool gets its own config file - auto-detected on project open.

rails ai:serve
→ rails_search_code(pattern: "publishable?", match_type: "trace")
→ rails_get_schema(table: "users")
→ rails_analyze_feature(feature: "billing")
</td> <td width="33%">

MCP Server (HTTP)

Mount inside your Rails app - inherits routing, auth, and middleware.

# config/routes.rb
mount RailsAiContext::Engine, at: "/mcp"

Native Rails controller transport. No separate process needed.

</td> <td width="33%">

CLI

Same 38 tools, no server needed. Works in any terminal, any AI tool.

rails 'ai:tool[search_code]' pattern="publishable?" match_type=trace
rails 'ai:tool[schema]' table=users
rails 'ai:tool[analyze_feature]' feature=billing
</td> </tr> </table>

Full Guide → - every command, every parameter, every configuration option.

<br>

Real-world examples

<details> <summary><strong>"Add a subscription field to users"</strong></summary> <br>
rails 'ai:tool[schema]' table=users
## Table: users
| Column              | Type    | Null | Default |
|---------------------|---------|------|---------|
| email               | string  | NO   | [unique] |
| subscription_status | string  | yes  | "free"   |
| created_at          | datetime| NO   |          |

AI sees subscription_status already exists. Checks the model, then generates a correct migration - first attempt.

</details> <details> <summary><strong>"Fix the broken post creation flow"</strong></summary> <br>
rails 'ai:tool[controllers]' controller=PostsController action=create
# PostsController#create

Filters: before_action :authenticate_user!, before_action :set_post (only: show, edit)
Strong params: post_params → title, body, published_at
Renders: redirect_to @post | render :new

AI sees the inherited authenticate_user! filter, the actual strong params, and the render paths. No guessing.

</details> <details> <summary><strong>"Build a new dashboard view"</strong></summary> <br>
# Check existing view patterns
rails 'ai:tool[view]' controller=dashboard
# → templates with ivars, Turbo frames, Stimulus controllers, partial locals

# See existing components + usage examples
rails 'ai:tool[component_catalog]' detail=standard
# → ViewComponent/Phlex props, slots, previews, sidecar assets

# Get Stimulus data-attributes
rails 'ai:tool[stimulus]' controller=chart
# → correct HTML with dashes (not underscores) + reverse view lookup
</details> <br>

38 Tools

Every tool is read-only and returns data verified against your actual app - not guesses, not training data.

<details open> <summary><strong>Search & Trace</strong></summary>
ToolWhat it does
search_codeTrace: definition + source + callers + tests. Also: definition, call, class filters
get_edit_contextMethod-aware code extraction with class context
</details> <details open> <summary><strong>Understand</strong></summary>
ToolWhat it does
analyze_featureFull-stack: models + controllers + routes + services + jobs + views + tests
get_contextComposite: schema + model + controller + routes + views in one call
onboardNarrative app walkthrough (quick/standard/full)
</details> <details open> <summary><strong>Schema & Models</strong></summary>
ToolWhat it does
get_schemaColumns with indexed/unique/encrypted/default hints
get_model_detailsAST-parsed associations, validations, scopes, enums, macros - each result tagged [VERIFIED] or [INFERRED]
get_callbacksCallbacks in Rails execution order with source
get_concernConcern methods + source + which models include it
</details> <details open> <summary><strong>Controllers & Routes</strong></summary>
ToolWhat it does
get_controllersActions + inherited filters + render map + strong params
get_routesCode-ready helpers (post_path(@record)) + required params
</details> <details open> <summary><strong>Views & Frontend</strong></summary>
ToolWhat it does
get_viewTemplates with ivars, Turbo wiring, Stimulus refs, partial locals
get_stimulusHTML data-attributes (dashes!) + targets + values + actions
get_partial_interfaceWhat locals to pass + what methods are called on them
get_turbo_mapBroadcast → subscription wiring + mismatch warnings
get_frontend_stackReact/Vue/Svelte/Angular, Hotwire, TypeScript, package manager
</details> <details open> <summary><strong>Testing & Quality</strong></summary>
ToolWhat it does
get_test_infoFixtures + relationships + test template matching your patterns
generate_testTest scaffolding matching your project's patterns
validateSyntax + semantic + Brakeman security in one call
security_scanBrakeman static analysis - SQL injection, XSS, mass assignment
performance_checkN+1 risks, missing indexes, counter_cache, eager load candidates
</details> <details open> <summary><strong>App Config & Services</strong></summary>
ToolWhat it does
get_conventionsAuth checks, flash messages, create action template, test patterns
get_configDatabase, auth framework, assets, cache, queue, Action Cable
get_gemsNotable gems with versions, categories, config file locations
get_envEnvironment variables + credentials keys (not values)
get_helper_methodsApp + framework helpers with view cross-references
get_service_patternInterface, dependencies, side effects, callers
get_job_patternQueue, retries, guard clauses, broadcasts, schedules
get_component_catalogViewComponent/Phlex: props, slots, previews, sidecar assets
</details> <details open> <summary><strong>Data & Debugging</strong></summary>
ToolWhat it does
dependency_graphModel/service dependency graph in Mermaid or text format
migration_advisorMigration code generation with reversibility + affected models
search_docsBundled topic index with weighted keyword search
querySafe read-only SQL with timeout, row limit, column redaction
read_logsReverse file tail with level filtering and sensitive data redaction
diagnoseOne-call error diagnosis with classification + context + git + logs
review_changesPR/commit review with per-file context + warnings
runtime_infoLive DB pool, table sizes, pending migrations, cache stats, queue depth
session_contextSession-aware context tracking across tool calls
</details>

All 38 tools with parameters →  |  Real-world recipes →

<br>

Live Resources (VFS)

AI clients can also read structured data through resource templates - rails-ai-context:// URIs that introspect fresh on every request. Zero stale data.

Resource TemplateWhat it returns
rails-ai-context://controllers/{name}Actions, inherited filters, strong params
rails-ai-context://controllers/{name}/{action}Action source code with applicable filters
rails-ai-context://views/{path}View template content (path traversal protected)
rails-ai-context://routes/{controller}Live route map filtered by controller
rails://models/{name}Per-model details: associations, validations, schema

Plus 9 static resources (schema, routes, conventions, gems, controllers, config, tests, migrations, engines) that AI clients read directly.

<br>

Anti-Hallucination Protocol

Every generated context file ships with 6 rules that force AI verification before writing code. The protocol targets the exact cognitive failures that produce confident-wrong code: statistical priors overriding observed facts, pattern completion beating verification, stale context lies.

<details> <summary><strong>The 6 rules (shown to AI in every CLAUDE.md / .cursor/rules / .cursorrules / .github/instructions)</strong></summary> <br>
  1. Verify before you write. Never reference a column, association, route, helper, method, class, partial, or gem not verified in THIS project via a tool call in THIS turn. Never invent names that "sound right."
  2. Mark every assumption. If proceeding without verification, prefix with [ASSUMPTION]. Silent assumptions forbidden. "I'd need to check X first" is a preferred answer.
  3. Training data describes average Rails. This app isn't average. When something feels "obviously" standard Rails, query anyway. Check rails_get_conventions + rails_get_gems BEFORE scaffolding.
  4. Check the inheritance chain before every edit. Inherited before_action filters, concerns, includes, STI parents. Inheritance is never flat.
  5. Empty tool output is information, not permission. "0 callers found" signals investigation, not license to proceed on guesses.
  6. Stale context lies. Re-query after writes. Earlier tool output may be wrong after edits.

Enabled by default. Disable with config.anti_hallucination_rules = false if you prefer your own rules.

</details> <br>

How it works

graph TD
    A["Your Rails App\nmodels + schema + routes + controllers + views + jobs"] -->|"39 introspectors"| B

    B["rails-ai-context\nPrism AST parsing · Cached · Confidence-tagged\nVFS: rails-ai-context:// URIs introspected fresh"]

    B --> C["MCP Server\nstdio / HTTP\n38 tools · 5 templates"]
    B --> D["CLI Tools\nRake / Thor\nSame 38 tools"]
    B --> E["Static Files\nCLAUDE.md · .cursor/rules/ · .cursorrules\n.github/instructions/"]

    style A fill:#4a9eff,stroke:#2d7ad4,color:#fff
    style B fill:#2d2d2d,stroke:#555,color:#fff
    style C fill:#0984e3,stroke:#0770c2,color:#fff
    style D fill:#00cec9,stroke:#00b5b0,color:#fff
    style E fill:#a29bfe,stroke:#8c83f0,color:#fff
<br>

Install

Option A - In Gemfile:

gem "rails-ai-context", group: :development
rails generate rails_ai_context:install

Option B - Standalone (no Gemfile entry needed):

gem install rails-ai-context
cd your-rails-app
rails-ai-context init

Both paths ask which AI tools you use (Claude Code, Cursor, GitHub Copilot, OpenCode, Codex CLI) and whether you want MCP or CLI mode. Each tool gets its own MCP config file - auto-detected on project open.

<br>

Commands

In-GemfileStandaloneWhat it does
rails ai:contextrails-ai-context contextGenerate context files
rails 'ai:tool[NAME]'rails-ai-context tool NAMERun any of the 38 tools
rails ai:toolrails-ai-context tool --listList all available tools
rails ai:serverails-ai-context serveStart MCP server (stdio)
rails ai:doctorrails-ai-context doctorDiagnostics + AI readiness score
rails ai:watchrails-ai-context watchAuto-regenerate on file changes
<br>

Documentation

Quickstart5-minute getting started
Tools ReferenceAll 38 tools with every parameter
RecipesReal-world workflows and examples
Custom ToolsBuild and test your own MCP tools
Configuration40+ config options with defaults
AI Tool SetupClaude, Cursor, Copilot, OpenCode, Codex
ArchitectureSystem design and internals
IntrospectorsAll 39 introspectors and AST engine
Security4-layer SQL safety and file blocking
CLI ReferenceCommands and argument syntax
StandaloneUse without Gemfile entry
TroubleshootingCommon issues and fixes
FAQFrequently asked questions
<br>

Build your own tools

Register custom MCP tools alongside the 38 built-in ones:

# app/mcp_tools/rails_get_business_metrics.rb
class RailsGetBusinessMetrics < MCP::Tool
  tool_name "rails_get_business_metrics"
  description "Key business metrics for this app"

  def call(period: "week")
    MCP::Tool::Response.new([{ type: "text", text: "Users this #{period}: #{User.recent.count}" }])
  end
end

# config/initializers/rails_ai_context.rb
config.custom_tools = [RailsGetBusinessMetrics]

Test with the built-in TestHelper (works with RSpec and Minitest):

include RailsAiContext::TestHelper

response = execute_tool("business_metrics", period: "month")
assert_tool_response_includes(response, "Users")

Custom Tools Guide →

<br>

Configuration

# config/initializers/rails_ai_context.rb
if defined?(RailsAiContext)
  RailsAiContext.configure do |config|
    config.ai_tools   = %i[claude cursor] # Which AI tools to generate for
    config.tool_mode  = :mcp              # :mcp (default) or :cli
    config.preset     = :full             # :full (39 introspectors) or :standard (17)
  end
end

All 40+ configuration options →

<br>

Observability

Every MCP tool call fires an ActiveSupport::Notifications event:

ActiveSupport::Notifications.subscribe("rails_ai_context.tools.call") do |event|
  Rails.logger.info "[MCP] #{event.payload[:method]} - #{event.duration}ms"
end
<br>

Requirements

  • Ruby >= 3.2    Rails >= 7.1
  • Optional: brakeman for security scanning, listen for watch mode, ripgrep for fast search
<br>
<div align="center">

About

Built by a Rails developer with 10+ years of production experience.<br> 2154 tests + 100-example e2e harness. 38 tools. 5 resource templates. 39 introspectors. Standalone or in-Gemfile.<br> MIT licensed. Contributions welcome.

<br>

If this gem saves you time, consider sponsoring the project.

<br>

MIT License

</div>

Related MCP servers

MCP server for Frida reverse engineering toolkit—inspect processes, load instrumentation scripts, and search CodeShare.

32
Go
MIT
View repository →

Read-only GitHub bounty, agent harness, Actions failure, flake, and MCP tool-drift decisions.

0
TypeScript
MIT
View repository →

MCP server for Croit Ceph cluster management with dynamic OpenAPI tool generation

1
Python
View repository →

MCP server for generating advanced mock 2D PNG assets for game prototypes.

3
TypeScript
MIT
View repository →

Memória de consumo: lista de compras, cupom fiscal e o que está faltando na despensa.

View repository →
NFNFe Hub logo

NFe Hub

Maintained

Consulta status de NFe na SEFAZ pela chave de acesso: autorizada, cancelada, protocolo.

0
View repository →