rails-ai-context
Provides tools for inspecting Stimulus controllers, actions, and targets within a Rails application, giving AI assistants context about the frontend JavaScript framework usage in the app.
Provides tools for understanding Turbo configuration and usage in a Rails application, including Turbo frames, streams, and drive behavior.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@rails-ai-contextshow me the schema for the users table"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
rails-ai-context
Your AI coding assistant, reading your real Rails app instead of guessing it.
Install in one paste · Why · What you get · Tools · Commands · Docs

rails-ai-context makes your Rails app the source of truth for your AI coding assistant. The assistant stops guessing your schema, associations, routes and conventions from training data and asks your app instead: 35 read-only tools over MCP or the command line, plus context files written for Claude Code, Cursor, GitHub Copilot, OpenCode and Codex CLI.
Install in one paste
Open your AI tool at the root of your Rails app and paste this. It installs the gem, sets up the AI tool you're in, checks the result and tells you the one step left.
Install the rails-ai-context gem in this Rails app so you can read its schema, models, routes and code through its tools instead of guessing.
1. Run `ruby -v` and `bundle exec rails -v`. rails-ai-context needs Ruby 3.1+ and Rails 7.0+. If either is older, stop and tell me.
2. Pick TOOL, the key for the AI tool you are: claude (Claude Code), cursor (Cursor), copilot (GitHub Copilot in VS Code), opencode (OpenCode), codex (Codex CLI). If you are another AI tool, stop and tell me to use the "Another MCP client" prompt instead.
3. Run `bundle add rails-ai-context --group development --version '>= 5.35.0'`. If the Gemfile already lists it, run `bundle update rails-ai-context --conservative` instead. Then run `bundle exec rails-ai-context version`: it must print 5.35.0 or newer, the first version with the flags used below. If it is older, the Gemfile pins it: change its rails-ai-context line to `gem "rails-ai-context", ">= 5.35.0", group: :development` and run `bundle update rails-ai-context --conservative`. If Bundler refuses (a frozen or deployment bundle), run `gem install rails-ai-context -v '>= 5.35.0'` instead and use `rails-ai-context init --tools TOOL --defaults` in step 4.
4. Run `bundle exec rails generate rails_ai_context:install --tools TOOL --defaults`. If it fails because the app can't boot, run `bundle exec rails-ai-context init --tools TOOL --defaults` instead; that one reads the source files when the app won't start.
5. Run `bundle exec rails-ai-context tool onboard` (or `rails-ai-context tool onboard` if you used gem install) and check it describes this app.
6. Tell me which files changed, then the "Next step" lines the install printed for TOOL, word for word. I have to do that step before your rails-ai-context MCP tools appear.Something else in mind? There's a prompt for it
The gem lives in your Ruby, the app's bundle stays as it is | |
No MCP server. The assistant runs the tools as shell commands | |
The server and nothing else. Your | |
All five AI tools, so everyone who opens the repo gets it | |
One editor window, several apps, one MCP server each | |
Works on your machine, | |
See what your assistant would get. Writes nothing | |
Mounted inside the running app, for clients that connect by URL | |
The server runs in your container, your AI tool on your machine | |
Claude Desktop, Windsurf, Zed, JetBrains: an entry that starts from any folder |
Already installed? Prompts to change the setup, switch install type, upgrade, fix it, uninstall, and put it to work. Every one gives each install answer as a flag, so it never stalls on a question in the AI tool's terminal.
In the Gemfile:
bundle add rails-ai-context --group development
bin/rails generate rails_ai_context:install # asks which AI tools and what to write
bin/rails generate rails_ai_context:install --tools claude --defaults # asks nothingStandalone, with no Gemfile change:
gem install rails-ai-context
rails-ai-context init # or: rails-ai-context init --tools claude --defaults--tools takes claude, cursor, copilot, opencode, codex or all. Add --cli for context files only, or --mcp-only for the MCP config only. Re-running is safe: with --defaults it keeps your recorded tools and setup, keeps what you have and adds what is missing, and in a CLAUDE.md you wrote it only touches the block between its <!-- BEGIN/END rails-ai-context --> markers. Every step is in What the install generator does.
Needs Ruby 3.1+ and Rails 7.0+, on Linux, macOS or Windows. Optional: brakeman for security_scan, listen for watch, ripgrep for faster search_code.
Then one step in your AI tool
Every AI tool holds a new project MCP server back until you say yes. The install prints the step for each tool you picked:
Claude Code | Cursor | GitHub Copilot | OpenCode | Codex CLI |
New session in the app's folder, approve | Restart, turn it on under MCP in Customize | Trust the workspace, send a chat message. Check with "MCP: List Servers" | Restart in the app's folder. Check with | Trust the project, start a new session. Check with |
Then ask something only your app knows, such as "what columns does the users table have?", and watch it call rails_get_schema instead of guessing.
Related MCP server: Synapse
Why
You have seen your assistant do these:
Write a migration for a column that already exists.
Call
user.postswhen the association isuser.articles.Scaffold tests with FactoryBot in a fixture-based suite.
Miss a
before_actioninherited from a parent controller, then wonder why auth fails.Add a gem you already have, or call an API from one you don't.
Invent a method that isn't in the codebase.
You catch it, fix it, re-prompt, and something next to it breaks. The tokens are cheap, but the correction loop costs you the afternoon. This gem removes the guess at the source.
You ask the AI to... | Without | With |
Add a | Writes the migration, duplicates an existing column | Reads the live schema, sees |
Call | Guesses; | Resolves the real association from the model |
Write tests for a new model | Scaffolds with FactoryBot | Detects your fixture-based suite and matches it |
Fix a failing create action | Misses the inherited | Gets parent-controller filters inline with the action source |
Build a dashboard page | Invents Tailwind classes from memory | Gets your real button, card and alert patterns |
Trace where | Reads 6 files in sequence, still misses callers | One call: definition, source, every caller, tests |

What you get
35 read-only tools | Schema, models, controllers, routes, views, Stimulus, Turbo, jobs, services, mailers, i18n, gems, config, tests, security, performance and more. Every answer comes from your app. |
Answers it can trust | Models are read with the Prism parser. A model and each scope carry |
Three ways in | MCP over stdio, MCP mounted in your app over HTTP, or plain CLI in any terminal. |
Context files per AI tool |
|
Works on apps that won't boot | Missing ENV vars, no database, a broken initializer: the tools answer from |
Real app shapes | Packwerk packs, in-repo engines, multi-database dumps, Mongoid, API-only apps, a folder holding several apps. |
Read-only and careful | SQL runs read-only with a timeout, a row limit and column redaction. Logs are redacted before they leave the process. Secrets files are never served. |
Yours to extend | Register your own |
Pick a setup
Setup | Writes | Flag | Good for |
MCP + context files | MCP config and context files |
| Most apps |
CLI only | Context files that name shell commands |
| Tools without MCP, or no server to approve |
MCP only | MCP config only |
| Teams that keep their own |
Switch any time with the change the setup prompt, or run the install again with the new flag and --prune.
How it works
graph TD
A["Your Rails app\nmodels + schema + routes + controllers + views + jobs"] -->|"40 introspectors"| B
B["rails-ai-context\nPrism AST · cached · confidence-tagged\nstatic tier when the app can't boot"]
B --> C["MCP server\nstdio / HTTP\n35 tools · 5 templates · 9 resources"]
B --> D["CLI\nrake / Thor\nsame 35 tools"]
B --> E["Context files\nCLAUDE.md · .cursor/rules/ · .github/instructions/ · AGENTS.md"]
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:#fffInternals are in Architecture and Introspectors.
Tools
Every tool is read-only and answers from your app.
Category | Tools |
Search and trace |
|
Understand |
|
Schema and models |
|
Controllers and routes |
|
Views and frontend |
|
Testing and quality |
|
App config and services |
|
Data and debugging |
|
Four worth knowing on day one:
search_codewithmatch_type=tracereturns the definition, the source, every caller grouped by file and labelled by type, and the tests, in one call. That replaces 4 to 5 file reads.get_controllersreturns the action source with inherited filters, strong params and the render map.get_model_detailsreturns associations, validations, scopes, enums and macros from the AST, tagged[VERIFIED]or[INFERRED].queryruns read-only SQL with a timeout, a row limit and column redaction.
Over MCP each name gets a rails_ prefix (rails_get_schema). From the CLI the short name works: schema, get_schema and rails_get_schema all resolve. Parameters for all 35 are in the tools reference; worked examples in recipes.
MCP clients can also read structured data as resources. Templates introspect fresh on every request:
URI | Returns |
| Associations, validations, schema for one model |
| Actions, inherited filters, strong params |
| Action source with the filters that apply |
| View template content (path traversal blocked) |
| Live route map for one controller |
The legacy rails://models/{name} form is still accepted. Plus 9 static resources: rails://schema, routes, conventions, gems, controllers, config, tests, migrations, engines.
Each AI tool's main context file (CLAUDE.md, AGENTS.md for OpenCode and Codex, .cursorrules and .cursor/rules/rails-mcp-tools.mdc for Cursor, .github/copilot-instructions.md) starts with six rules the assistant reads before writing code, in compact and full mode alike. With generate_root_files off, .claude/rules/rails-mcp-tools.md and .github/instructions/rails-mcp-tools.instructions.md carry them instead:
Verify before you write. Never reference a column, association, route, helper, method, class, partial or gem that a tool call in this turn did not confirm.
Mark every assumption with
[ASSUMPTION]. "I'd need to check X first" is a good answer.Training data describes average Rails. This app isn't average. When something feels obviously standard, query anyway.
Check the inheritance chain before every edit: inherited filters, concerns, includes, STI parents.
Empty tool output is information. "0 callers found" means investigate, it does not mean proceed.
Stale context lies. Re-query after writes.
On by default. Turn off with config.anti_hallucination_rules = false if you prefer your own. In an MCP-only or CLI setup, the ground rules prompt gives the assistant the same rules for one session.
Three ways to connect
MCP over stdio is the default. Each AI tool gets its own config file (.mcp.json, .cursor/mcp.json, .vscode/mcp.json, opencode.json, .codex/config.toml) that starts bundle exec rails-ai-context serve, or rails-ai-context serve standalone. On Windows each starts it through cmd /c, since a gem's executables there are batch files.
MCP over HTTP mounts the server inside your app, where it inherits your routing, auth and middleware:
# config/routes.rb
mount RailsAiContext::Engine, at: "/mcp" if defined?(RailsAiContext::Engine)The if keeps the routes file loading where the gem is not installed, as in production, where Bundler skips the development group. Outside development and test the endpoint refuses every request with a 403 unless you set config.allow_http_in_production = true, since it has no authentication of its own (Security). There is also a standalone HTTP process: rails-ai-context serve --transport http --port 6029.
CLI runs the same 35 tools with no server, in any terminal:
bin/rails 'ai:tool[search_code]' pattern="publishable?" match_type=trace
rails-ai-context tool schema --table users --detail fullAbout half the tools take detail=summary|standard|full.
When the app can't boot
The app-reading commands try a full boot for live reflection. When boot fails (missing ENV vars, an unreachable service, a broken initializer) they fall back to the static tier instead of dying: routes from config/routes.rb, schema from db/schema.rb, db/structure.sql or migrations, models and controllers from their source. Every response carries a banner naming the degradation, static data is tagged [STATIC], and a section that needs a booted app says [UNAVAILABLE] with the reason. --no-boot skips the attempt outright. doctor still needs a bootable app, since diagnosing the boot is its job.
Code is found in the conventional layout, in packwerk packs (packs/*/app/*), in in-repo engines (engines/*/app/*), and in any extra_app_paths from .rails-ai-context.yml. Details in Compatibility.
Commands
In the Gemfile | Standalone | What it does |
|
| Set up (both take |
|
| Start the MCP server (stdio) |
|
| Start the MCP server (HTTP) |
|
| Run one tool |
|
| List the tools |
|
| Regenerate the context files |
|
| Diagnostics and a readiness score |
|
| Regenerate on file change |
|
| Run a multi-tool preset ( |
|
| Remove what the gem wrote, keep what you wrote |
|
| Print an MCP entry for Claude Desktop, Windsurf, Zed and other clients |
The binary finds the app the way bin/rails does, so it runs from any subdirectory. Flags shared by the app-reading commands: --app-path PATH to target another directory, --environment ENV to set RAILS_ENV, and --no-boot to answer from source. Full list in the CLI reference.
These commands are for you. With MCP connected the assistant calls the same tools itself.
Configuration
# config/initializers/rails_ai_context.rb
if defined?(RailsAiContext) && RailsAiContext.respond_to?(:configure)
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 (40 introspectors) or :standard (17)
end
endStandalone installs use the same keys in .rails-ai-context.yml. All options with defaults are in Configuration.
Register your own tools next to the 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"
input_schema(properties: { period: { type: "string" } })
def self.call(period: "week", server_context: nil)
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 them with the bundled helper (RSpec or Minitest):
include RailsAiContext::TestHelper
response = execute_tool("business_metrics", period: "month")
assert_tool_response_includes(response, "Users")See Custom tools.
Every MCP call fires an ActiveSupport::Notifications event:
ActiveSupport::Notifications.subscribe("rails_ai_context.tools.call") do |event|
ms = (event.payload[:duration].to_f * 1000).round
Rails.logger.info "[MCP] #{event.payload[:tool_name]} #{ms}ms"
endUninstall
bundle exec rails-ai-context uninstall && bundle remove rails-ai-context # in the Gemfile
rails-ai-context uninstall # standaloneIt removes the context files, the MCP entries, its config, its .gitignore lines and its pre-commit hook, and keeps what you wrote: your lines in CLAUDE.md, other servers in an MCP config, a hook you edited. Or paste the uninstall prompt.
Documentation
Let your AI tool install, change, remove or use the gem | |
Up and running in 5 minutes | |
Claude Code, Cursor, Copilot, OpenCode, Codex CLI, HTTP transport | |
Every command, parameter and option | |
All 35 tools with every parameter | |
Real workflows, end to end | |
Commands, flags and argument syntax | |
Use without a Gemfile entry | |
Every option with its default | |
Build and test your own tools | |
System design and internals | |
All 40 introspectors and the AST engine | |
SQL safety layers and file blocking | |
Supported versions, operating tiers, app shape matrix | |
Common problems and fixes | |
Frequently asked questions |
If it saves you a correction loop, star it on GitHub.
Built by a Rails developer with 10+ years in production. If it saves you time, consider sponsoring the project.
This server cannot be deployed
Maintenance
Related MCP Connectors
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
Read-only AI coding tools for change verification, release readiness, capacity, and guidance.
Read-only MCP tools for AI agent discovery, structured resources, and NIULAI information.
A registry of AI agent tools — MCP servers, APIs, CLIs, SDKs — kept current by automated ingestion.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceProvides MCP tools that help AI agents get their bearings in a codebase with unified SQL views over code, git, docs, and conversations, powered by DuckDB.54 PyPI5Apache 2.0
- FlicenseNot gradedqualityDmaintenanceProvides structural code intelligence via 26 MCP tools, enabling AI assistants to query code symbols, dependencies, and call graphs accurately without file-pasting.-
- AlicenseAqualityCmaintenanceEnables AI coding agents to efficiently explore codebases by providing structural outlines, module digests, symbol bodies, and AST-aware grep via MCP.427 npm1MIT

Tidewave Railsofficial
AlicenseNot gradedqualityAmaintenanceBetter agentic Rails development, runtime-level tools for your agent to talk to your running app.476Apache 2.0