rails-ai-context - Complete Guide
The all-in-one rails-ai-context reference: every command, parameter and option in one file.
Quickstart · Tools · Recipes · FAQ
NoteThis is the full single-file reference. For focused guides, see the docs below. For a quick overview, see the Home.
Focused guides
| Guide | Description |
|---|---|
| Quickstart | Get running in 5 minutes |
| Copy-paste prompts | Let your AI tool install, change, remove or use the gem |
| Tools Reference | All 35 MCP tools with parameters |
| Recipes | Real-world workflows and examples |
| Custom Tools | Build your own MCP tools |
| Configuration | Every config option |
| AI Tool Setup | Per-editor setup |
| Architecture | System design and internals |
| Introspectors | All 40 introspectors |
| Security | Security model and SQL safety |
| CLI Reference | All commands and argument syntax |
| Standalone Mode | Use without Gemfile |
| Troubleshooting | Common issues and fixes |
| FAQ | Frequently asked questions |
Table of Contents
- Installation
- Uninstalling
- Context Modes
- Generated Files
- All Commands
- CLI Tools
- MCP Tools - Common Reference
- MCP Resources
- MCP Server Setup
- Configuration - All Options
- Introspectors - Full List
- AI Assistant Setup
- Stack Compatibility
- Diagnostics
- Watch Mode
- Works Without a Database
- Security
- Troubleshooting
Installation
Option A: In Gemfile
gem "rails-ai-context", group: :development
bundle install
rails generate rails_ai_context:install
rails ai:context
This creates:
config/initializers/rails_ai_context.rb- configuration file.rails-ai-context.yml- standalone config (enables switching later)- Per-tool MCP config files - each AI tool finds its own when it opens the project, then asks you to approve the server once
- Context files - tailored for each AI assistant
Option B: Standalone (no Gemfile entry needed)
gem install rails-ai-context
cd your-rails-app
rails-ai-context init
This creates:
.rails-ai-context.yml- configuration file- Per-tool MCP config files - in the MCP and MCP-only setups
- Context files - tailored for each AI assistant
No Gemfile entry, no initializer, no files in your project besides config and context.
What the install generator does
rails generate rails_ai_context:install runs these steps in this order. Steps 1, 2, 3, 4, 8 and 9 can ask a question.
-
Asks which AI tools you use. It prints this menu, then
Enter numbers separated by commas (e.g. 1,2) or 'a' for all (default: all):, or(default: keep the current selection):on a re-run1. Claude Code -> CLAUDE.md + .claude/rules/ 2. Cursor -> AGENTS.md + .cursor/rules/ 3. GitHub Copilot -> .github/copilot-instructions.md + .github/instructions/ 4. OpenCode -> AGENTS.md 5. Codex CLI -> AGENTS.md + .codex/config.toml a. All of the aboveOn a re-run the menu is followed by the selection recorded last time, as
Currently selected: 1,2 (Claude Code, Cursor). There is no "none" choice. An empty answer takes the default: the recorded selection on a re-run, all five on a first install. So does an answer with no valid number in it, which says so ("9" names no tool - keeping the current selection.). - Offers to clean up tools you dropped. Only on a re-run, and only when the last recorded selection (the
config.ai_toolsline in the initializer, else.rails-ai-context.yml) has a tool you did not pick this time. It lists them and asksRemove their generated files?withy(all),n(keep, the default) or numbers like1,2. A yes removes only what the gem generated: the rule files it names inside the tool's rules directory (the directory goes too when nothing else is left in it), and the block between therails-ai-contextmarkers in a root file such asCLAUDE.md. A rule file you wrote by hand, your own lines around the markers, a root file with no markers and a symlinked folder are left alone. A root file that is a symlink to a file inside the app loses its block through the link, as the writer wrote it there, and one that leads out of the app is left and named. It keeps any file shared with a tool whose files stay (AGENTS.md) - one still selected, or one dropped whose files you kept by leaving its number out - and says so, and takes only therails-ai-contextentry out of the tool's MCP config - a config left with no other entry is deleted, and named as removed. A tool's dot-directory the cleanup emptied (.cursor/,.github/,.codex/,.vscode/) goes too; one that still holds a file of yours stays. -
Asks what to write, then
Enter number (default: 1):. On a re-run it first prints the recorded setup (Currently: Context files only (CLI mode, no MCP server)), and that is the default1. MCP config + context files (default) 2. Context files only (CLI mode, no MCP server) 3. MCP config only (writes no CLAUDE.md, AGENTS.md or rules files)Choices 1 and 3 set
tool_modeto:mcp, choice 2 sets it to:cli. Choice 3 also setscontext_filestofalse. Any other answer takes the default. - Writes the MCP config for each selected tool (
.mcp.json,.cursor/mcp.json,.vscode/mcp.jsonand.github/mcp.json,opencode.json,.codex/config.toml). Skipped for choice 2, which instead lists any config that still startsrails-ai-contextand asksRemove rails-ai-context from them? (y/N): CLI mode starts no MCP server. A yes takes out only the gem's entries, as step 2 does. With choice 3 it lists instead the context files an earlier setup generated, which nothing refreshes once the install writes no context files, and asksRemove the generated parts? Lines you wrote stay. (y/N); a yes removes them the way step 2 does, and.ai-context.jsonwith them. An existing file is merged: only therails-ai-contextentry is added or updated, and keys in it the gem never writes stay. An entry under that name whose command the gem did not write (one that starts the server through Docker) is kept as it is, with a note. One that does not parse as JSON, or holds comments a rewrite would drop, is left as it is, with a warning that names the entry to add by hand. Each file is read as its client reads it. VS Code's and OpenCode's take JSONC, comments and trailing commas (read under json 2.9 or later); Claude Code reads.mcp.jsonas plain JSON, and Cursor's.cursor/mcp.jsonis held to plain JSON too, so a comment or a trailing comma in either is reported as one the client cannot read, and the file left as it is. In.codex/config.tomlthe server's table is found however its name is quoted, and replaced where it stands; an entry of the gem's written as an inline table or with dotted keys is left as it is, with a warning, since a table added beside it would declare the server twice, which Codex refuses. - Creates or updates
config/initializers/rails_ai_context.rb. A new file gets your three answers as live lines (config.ai_tools,config.tool_mode,config.context_files) and every other option commented out at its default, wrapped inif defined?(RailsAiContext) && RailsAiContext.respond_to?(:configure); it passes the omakase Rubocop a new Rails app runs. In an existing file it rewrites those three lines where the value changed - keeping the line's indentation and any note of your own after it - appends any config section the file lacks, adds the guard if it is missing (below the comments the file opens with, so a magic comment still applies), upgrades a bareif defined?(RailsAiContext)guard, and leaves the rest alone. - Writes
.rails-ai-context.ymlwithai_tools,tool_modeandcontext_files. Only a key whose value changed is rewritten, where it stands; your comments and other keys are kept, and a run that changes no value leaves the file as it was. - Adds a line to
.gitignore, if the file exists:.ai-context.json(not for choice 3). A line that is already there is not added again..codex/config.tomlis no longer added: it holds nothing machine-specific and is committed like the other MCP configs, so the line an earlier release added is taken out. - Asks about a pre-commit hook:
Install a pre-commit hook that checks staged Ruby, ERB and JavaScript files for syntax errors? (y/N). Onlyyinstalls it. The hook runsbundle exec rails-ai-context tool validate(rails-ai-context tool validatein a standalone install) on the staged.rb,.erb,.js,.mjsand.cjsfiles and stops a commit whose files do not parse (JavaScript is parsed bynode, asrails_validatedescribes); the Rails-reference checks (level=rails) are left to the tool, as Brakeman would slow every commit. An app that cannot boot (an initializer that needs a variable the shell lacks, say) is still checked, from its source, and the hook shows why it did not boot; it shows whatever else the check prints to stderr too, so a check that cannot run says why. Every staged name is read whole, one with characters outside ASCII included; a name holding a comma, which the files list cannot carry, is named and left unchecked. It goes where git runs hooks (git rev-parse --git-path hooks), so an app checked out as a submodule, an app inside a monorepo and a repo withcore.hooksPathset all get it where git will run it. The hook names the apps it covers and validates each one's staged files (deleted ones aside) from inside that app; installing in a second app of the same monorepo adds it to the hook, unless the hook was changed by hand, which it says, and for an app below the top of the repository the question names the repository. A hook an earlier version wrote, and nobody changed since, is brought up to date without asking again: the oldest handed validate the files a commit deletes too, and the commit failed on them, and later ones ranrails 'ai:tool[validate]', which has to boot the app, with its errors thrown away, so an app that could not boot failed every commit with no reason given. Any other hook that runsrails-ai-context- one changed by hand, or a team's own that calls it among other checks - is left as it is, with a message. No hook is offered for an app the repository does not track yet (an app under a dotfiles repository at$HOME, say), nor into acore.hooksPathoutside the repository, which every repository using it shares; both say why. No question is asked outside a git repository or when the hook already covers the app. When anotherpre-commithook exists there it printsSkipped pre-commit hook (existing hook found - add manually)and moves on. - Generates the context files for the selected tools. Skipped for choice 3. If files that v5.0.0 stopped generating are still there (
.claude/rules/rails-ui-patterns.md,.claude/rules/rails-accessibility.md,.cursor/rules/rails-ui-patterns.mdc,.github/instructions/rails-ui-patterns.instructions.md), it lists them first and asksDelete them? [y/N]:. Without a terminal, or under--defaults, it prints thermcommand and does not ask; under--pruneit deletes them without asking. Files an earlier run wrote that this run no longer writes go without a question, and the output names them: the block in.cursorrules, and an overview or tools rule the root file states (Generated Files). - Prints a summary: the files each selected tool got, the commands to run next, and, in the MCP setup, each tool's next step: the approval or trust step that tool asks for before it starts a project's MCP server (approve the server in Claude Code, turn it on in Cursor, trust the folder in VS Code and Codex CLI, restart OpenCode).
Every question has a flag, so an AI tool or a script can run the install to the end with nobody at the keyboard (the copy-paste prompts are built on them):
--tools claude,cursoranswers step 1. It takes the tool namesclaude,cursor,copilot,opencodeandcodex, comma-separated, orall; never the menu numbers, which would pick another tool once one is added.--mcpanswers step 3 with choice 1,--cliwith choice 2,--mcp-onlywith choice 3. Only one of them can be given.--pruneanswers yes to every removal question: step 2 (dropped tools' generated files), step 4's in the CLI setup (the gem's MCP entries) and in the MCP-only setup (the context files an earlier setup generated), and step 9's (legacy files).--hookanswers yes to step 8.--defaultsanswers every question no flag answered with its default. On a first install that is all five tools and choice 1; on a re-run it is the recorded tools and setup, so running the install again with--defaultsrepairs it without switching anything. Every removal question defaults to keep, and the hook to no. Piping an empty stdin does the same. A default never removes a file; only--prunedoes.
A flag the install cannot read (a name that is no tool, two setup flags at once, or a flag it does not have, such as a mistyped one) stops it with exit status 1 before anything is asked or written. ADR-0007 records the design.
Run from a mountable engine's root, where bin/rails boots test/dummy, the install goes into the engine's root - the folder an editor is opened at, and the one every rails-ai-context command run there reads: the MCP configs, .rails-ai-context.yml, the .gitignore lines and the context files, which are generated from the engine's source the way its MCP server reads it there. No initializer is written, since Rails runs an engine's config/initializers in every app that mounts it and the gemspec ships them; one an earlier install left there is named, with a note to delete it. Step 8 offers no hook at the engine's root (its rake tasks run in the dummy app, as app:ai:*), and the summary lists the commands that work at the engine's root, bundle exec rails-ai-context .... The context files written there name the same commands for their CLI fallback and the server, as do the tools' own hints. bundle exec rails-ai-context doctor at the engine's root diagnoses the dummy app and reads this install, as bin/rails app:ai:doctor does.
A team that wants no AI tool files in the repo can skip the generator. The gem needs none of its output: rails 'ai:tool[NAME]', rails ai:serve, rails ai:doctor and the rails-ai-context binary all work on the defaults with no initializer, no .rails-ai-context.yml and no MCP config. rails ai:context is the one to leave alone in that setup, since it writes context files. To make that safe too, set config.ai_tools = [] in an initializer: an empty list means no tool, so nothing is written and nothing is asked.
Two other entry points ask the same step 1 and step 3 questions:
rails-ai-context init(standalone) asks both, then the step 2 cleanup question, step 4's question about MCP configs when the answer was the CLI setup or about generated context files when it was MCP only, and the step 9 question. Only then does it boot the app, so that every gem the app locks loads at the app's pin, and write: the cleanup,.rails-ai-context.yml, the MCP configs, the.gitignorelines and the context files. An MCP-only run skips the step 9 question, as the generator does, and boots nothing. It never creates the initializer (in one that exists it updatesconfig.ai_tools,config.tool_modeandconfig.context_files), never offers the pre-commit hook, and takes the same flags as the generator but--hook:--tools,--mcp,--cli,--mcp-only,--pruneand--defaults. Typed outside the app (init --app-path ../shop), it names the files it wrote from there, as../shop/.mcp.json. Run in a folder that holds several apps, it asks once and sets them all up: each app's own.rails-ai-context.ymland context files, and one MCP server per app in the folder's configs (init).rails ai:contextasks step 1 only when no tool selection is recorded, and step 3 only when notool_modeis recorded. It then writes.rails-ai-context.yml, the MCP configs and the.gitignorelines before generating. It does not create the initializer or offer the hook.rails-ai-context contextbrings the MCP configs of a recorded selection up to date the same way, andrails ai:context:<tool>writes that tool's MCP config along with its files.
Uninstalling
bundle exec rails-ai-context uninstall # in the Gemfile; then: bundle remove rails-ai-context
rails-ai-context uninstall # standalone; then, once no app uses it: gem uninstall rails-ai-context
uninstall takes out what the gem wrote and nothing you wrote:
- Each AI tool's context files. A rules file you wrote stays, and in a root file such as
CLAUDE.mdonly the block between therails-ai-contextmarkers goes, so your own lines stay. A file left empty is deleted, and so is a tool's dot-directory (.cursor/,.claude/) once nothing of yours is in it. - The
rails-ai-contextentry in every MCP config, an HTTP one under that name included. Other servers in the file stay; a config left with none is deleted. An entry under the gem's name that starts its server some other way (through Docker, say) or holds a key you added is yours: it stays, and is named with its file. .rails-ai-context.yml,.ai-context.jsonandconfig/initializers/rails_ai_context.rb, edited or not: they configure nothing once the gem is gone.- The lines the install added to
.gitignore, with their comments. - The pre-commit hook, when it is the one the install wrote and covers only this app. A hook that covers other apps of the repository loses this one; a hook changed by hand is named and left for you.
A mount RailsAiContext::Engine line in config/routes.rb is your code, so it is named with its line number, not edited. Run in a folder of apps, it does the same for every app below and for the folder's MCP configs. It needs no boot, so it works on an app that cannot start, and the binary of any install can run it: in an app whose bundle pins a version from before uninstall existed, gem install rails-ai-context and run rails-ai-context uninstall. Where the Claude Code plugin runs the gem, it first names the commands that turn the plugin off and take it out (SETUP); a release from before the plugin names none, so turn it off yourself with claude plugin disable rails-ai-context@rails-ai-context --scope local.
Context Modes
The gem has two context modes that control how much data goes into the generated files:
Compact mode (default)
rails ai:context
- The root file (AGENTS.md, CLAUDE.md or copilot-instructions.md) stays within
12,000 bytes and
claude_max_lines(150) non-blank lines. Over budget, the data sections are cut from the bottom; the title and the Commands, Warnings, Rules and Tools sections are never cut, so a budget smaller than they are (about 70 lines) leaves just them - It names the 10 most connected models. A list names what fits a 240-character line and ends with "...N more"; the tools answer the rest
- It holds a project overview and the tools guide. The guide gives each example
in the one form the tool mode uses (an MCP call, or a command in
:climode) and has one Rules list with no ALL-CAPS emphasis, since Claude Code's docs say piled-on emphasis makes Claude over-apply a rule. It lists the tool names only in:climode: an MCP client lists the tools itself - AI uses MCP tools for detailed data on-demand
- Best for: all apps, especially large ones (30+ models)
Full mode
rails ai:context:full
# or
CONTEXT_MODE=full rails ai:context
- Puts the whole introspection into the root file: every table with its column types, defaults, indexes and foreign keys; every model with its associations, validations, scopes, callbacks, enum values and constants; the app's own routes (the framework's are counted, not listed); Stimulus controllers; and the rest of the introspection. The rules files are the same in both modes
- The file stays within 24,000 bytes. A large app's data sections are cut from the bottom, with a note that the tools answer the rest; the header, the rules, the tools guide and the last line are never cut
- The root file ends with the same tools guide and anti-hallucination protocol the compact file carries, so OpenCode and Codex, which read AGENTS.md alone, get them too
- A plain
rails ai:contextwrites compact files again unlessconfig.context_modeis:full, so each file's last line names the command that keeps full mode:CONTEXT_MODE=full rails ai:context, or for a standalone installrails-ai-context context, which readscontext_modefrom.rails-ai-context.yml - Best for: small apps (<30 models), whose full dump fits the budget
Per-format with mode override
# Full dump in the root file Claude Code reads
CONTEXT_MODE=full rails ai:context:claude
# Full dump for Copilot only
CONTEXT_MODE=full rails ai:context:copilot
Where CLAUDE.md imports AGENTS.md, the first command writes the full dump into AGENTS.md, which Cursor, OpenCode and Codex read too.
Set mode in configuration
# config/initializers/rails_ai_context.rb
if defined?(RailsAiContext) && RailsAiContext.respond_to?(:configure)
RailsAiContext.configure do |config|
config.context_mode = :full # or :compact (default)
end
end
Generated Files
rails ai:context generates 19 files across all AI assistants. No run writes all of them: the three root files are written while generate_root_files is on (the default), and the six overview and tools rules only when it is off, since the root file states them otherwise.
The root content is written once, into a file every chosen AI tool reads. AGENTS.md carries it when Cursor, OpenCode or Codex is chosen: Cursor reads AGENTS.md and CLAUDE.md as it reads its own always-on rules (Cursor). CLAUDE.md then holds only @AGENTS.md, an import Claude Code expands at launch (Claude Code); without those three, CLAUDE.md carries the content itself. .github/copilot-instructions.md gets an identical copy, since github.com chat, Visual Studio, JetBrains, Xcode and code review read no other file (GitHub), and Copilot CLI drops identical copies.
Every file has a byte budget: 12,000 bytes for a compact root file, 24,000 in full mode, 8,000 for a rule file, and 12,000 for a tools rule that stands in for the root file. It is low on purpose, since these files share the agent's context with your own instructions, and Codex reads at most 32 KiB of project docs in all. A list names what fits a 240-character line and ends with "...N more"; the tools answer the rest.
A file whose section has nothing in it is not written. An app with no models gets no .claude/rules/rails-models.md, and every surface names the file and the reason so a deliberate omission is not mistaken for a failed run. rails ai:context and the installer print ➖ .claude/rules/rails-models.md (no models); the CLI and the watcher print Not applicable: .claude/rules/rails-models.md (no models). A rule the root file states is named the same way, with the reason in the root file.
A run removes the files an earlier run wrote that it no longer writes. The CLI and the watcher print Removed: PATH, or Removed the generated block from PATH where your own lines stay; rails ai:context and the installer mark it (removed) or (generated block removed). doctor counts a file a run would remove as out of date.
Claude Code (6 files)
| File | Purpose | Notes |
|---|---|---|
CLAUDE.md |
Root context file | Holds only @AGENTS.md where AGENTS.md carries the root content, and the content itself otherwise. Claude Code reads it at launch. |
.claude/rules/rails-schema.md |
Database table listing | Every database's tables, each database under its own heading when the app has more than one. A database of Solid Queue, Solid Cache or Solid Cable tables only, as Rails 8's queue, cache and cable are, is named in the root file instead (queue: Solid Queue (13 tables)). Loaded when Claude Code opens a schema dump or a migration. |
.claude/rules/rails-models.md |
Model listing with associations | Loaded when Claude Code opens a file in app/models/. |
.claude/rules/rails-context.md |
Project overview | Written only with generate_root_files off. Loaded in every session. |
.claude/rules/rails-mcp-tools.md |
Tools guide | Written only with generate_root_files off. Loaded in every session: the protocol, the workflows and the rules, as the root file carries them. |
.claude/rules/rails-components.md |
View component listing | Written only when the app has view components. Loaded when Claude Code opens a file in app/components/ or app/views/components/. |
OpenCode (3 files)
| File | Purpose | Notes |
|---|---|---|
AGENTS.md |
Root context file | Carries the root content for OpenCode, Codex and Cursor, and for Claude Code through the import in CLAUDE.md. OpenCode reads CLAUDE.md only where there is no AGENTS.md. |
app/models/AGENTS.md |
Model reference | Auto-loaded by OpenCode when reading files in app/models/. One you wrote yourself keeps its text, with the listing added between markers. |
app/controllers/AGENTS.md |
Controller reference | Auto-loaded by OpenCode when reading files in app/controllers/. One you wrote yourself keeps its text, with the listing added between markers. |
Cursor (5 files)
| File | Purpose | Notes |
|---|---|---|
AGENTS.md |
Root context file | The file OpenCode and Codex read too. Cursor reads it, and CLAUDE.md, like an always-on rule. |
.cursor/rules/rails-project.mdc |
Project overview | alwaysApply: true - loaded in every conversation. Written only with generate_root_files off. |
.cursor/rules/rails-models.mdc |
Model reference | globs: app/models/**/*.rb - auto-attaches when editing models. |
.cursor/rules/rails-controllers.mdc |
Controller reference | globs: app/controllers/**/*.rb - auto-attaches when editing controllers. |
.cursor/rules/rails-mcp-tools.mdc |
Tools guide | alwaysApply: true - loaded in every conversation. Written only with generate_root_files off. |
.cursorrules is no longer written: Cursor calls it legacy, and reads the content from AGENTS.md. With root files on, a run takes out the block an earlier release wrote there and keeps your own lines; a file that held only the block is deleted. Cleanup and doctor still know the file.
GitHub Copilot (5 files)
| File | Purpose | Notes |
|---|---|---|
.github/copilot-instructions.md |
Root context file | An identical copy where AGENTS.md or CLAUDE.md carries the root content too, since github.com chat, Visual Studio, JetBrains, Xcode and code review read no other file. |
.github/instructions/rails-models.instructions.md |
Model context | applyTo: app/models/**/*.rb - loaded when editing models. |
.github/instructions/rails-controllers.instructions.md |
Controller context | applyTo: app/controllers/**/*.rb - loaded when editing controllers. |
.github/instructions/rails-context.instructions.md |
Project overview | applyTo: **/* - loaded everywhere. Written only with generate_root_files off. |
.github/instructions/rails-mcp-tools.instructions.md |
Tools guide | applyTo: **/* - loaded everywhere but code review. Written only with generate_root_files off. |
Generic (1 file)
| File | Purpose | Notes |
|---|---|---|
.ai-context.json |
Full structured JSON | For programmatic access or custom tooling. Added to .gitignore. |
Which files to commit
Commit all files except .ai-context.json (which is gitignored). This gives your entire team AI-assisted context automatically.
Telling a static file from a booted one
A run that could not boot the app, or was given --no-boot, reads source files
instead of a running Rails. The counts differ, so every generated file that
states them says so: a [STATIC] line under the header, and a
"tier": "static" key in .ai-context.json. The MCP tool references carry no
app counts, so they carry no line. A booted run says nothing extra, so an
unmarked file was generated with the app running.
All Commands
Context generation
| Command | Mode | Format | Description |
|---|---|---|---|
rails ai:context |
compact | all | Generate all 19 context files |
rails ai:context:full |
full | all | Generate all files in full mode |
rails ai:context:claude |
compact | Claude | CLAUDE.md + .claude/rules/, and the AGENTS.md it imports when Cursor, OpenCode or Codex is selected too |
rails ai:context:opencode |
compact | OpenCode | AGENTS.md + per-directory AGENTS.md |
rails ai:context:codex |
compact | Codex | AGENTS.md + per-directory AGENTS.md (same files as OpenCode), and .codex/config.toml in MCP mode |
rails ai:context:cursor |
compact | Cursor | AGENTS.md + .cursor/rules/ |
rails ai:context:copilot |
compact | Copilot | copilot-instructions.md + .github/instructions/ |
rails ai:context:json |
- | JSON | .ai-context.json |
CONTEXT_MODE=full rails ai:context:claude |
full | Claude | Full dump in the root file Claude Code reads |
CONTEXT_MODE=full rails ai:context:opencode |
full | OpenCode | Full dump in AGENTS.md, which Codex and Cursor read too |
CONTEXT_MODE=full rails ai:context:copilot |
full | Copilot | Full dump for Copilot only |
The rules files are the same in both modes, so CONTEXT_MODE=full changes only the root file.
Each rails ai:context:<tool> adds its tool to the recorded selection and, in MCP mode, writes that tool's MCP config too (.cursor/mcp.json for Cursor), since its files tell the AI to call the MCP tools.
CLI tools
| Command | Description |
|---|---|
rails 'ai:tool[NAME]' |
Run any MCP tool from the CLI (e.g. rails 'ai:tool[schema]' table=users detail=full) |
rails ai:tool |
List all available tools with descriptions |
rails 'ai:tool[NAME]' JSON=1 |
Run tool with JSON envelope output |
MCP server
| Command | Transport | Description |
|---|---|---|
rails ai:serve |
stdio | Start MCP server. The generated MCP config files start the same server with bundle exec rails-ai-context serve. |
rails ai:serve_http |
HTTP | Start MCP server at http://127.0.0.1:6029/mcp. For remote clients. |
Utilities
| Command | Description |
|---|---|
rails ai:doctor |
Run the diagnostic checks that apply to the app. Reports pass/warn/fail with fix suggestions. AI readiness score (0-100). STRICT=1 exits 1 when a check fails. |
rails ai:watch |
Watch for file changes and auto-regenerate context files. Requires listen gem. |
rails ai:inspect |
Print introspection summary to stdout. Useful for debugging. |
rails ai:facts |
Print a short schema facts summary (tables, columns, indexes, associations, dependencies). |
rails 'ai:preset[NAME]' |
Run a multi-tool preset: architecture, debugging or migration. |
Standalone CLI
The gem ships a rails-ai-context executable that works without adding the gem to your Gemfile. Install globally with gem install rails-ai-context, then run from any Rails app directory.
rails-ai-context init # Setup: asks, or takes every answer as a flag (creates .rails-ai-context.yml + MCP configs)
rails-ai-context init --tools claude --defaults # The same, every answer given as a flag
rails-ai-context serve # Start MCP server (stdio)
rails-ai-context serve --transport http # Start MCP server (HTTP, port 6029)
rails-ai-context serve --transport http --port 8080 # Custom port
rails-ai-context context # Generate all context files
rails-ai-context context --format claude # Generate Claude files only
rails-ai-context tool # List all available tools
rails-ai-context tool schema --table users --detail full # Run a tool
rails-ai-context tool schema --help # Per-tool help
rails-ai-context tool schema --json # JSON envelope output
rails-ai-context doctor # Run diagnostics (--strict exits 1 on a failed check)
rails-ai-context watch # Watch for changes
rails-ai-context inspect # Print introspection JSON
rails-ai-context facts # Print schema facts summary
rails-ai-context preset architecture # Run a multi-tool preset
rails-ai-context uninstall # Remove what the gem wrote, keep what you wrote
rails-ai-context mcp-entry # Print an MCP entry for Claude Desktop, Windsurf, Zed and other clients
rails-ai-context version # Print version
rails-ai-context help # Show all commands
Run it anywhere inside your Rails app, from a folder holding one app, or pass --app-path PATH (how the app is found). Booting needs config/environment.rb. When the app cannot boot, or with --no-boot, every command except doctor reads the source files instead.
Config: Standalone mode reads from .rails-ai-context.yml (created by init), and that is its only config source - the gem is not loaded while config/initializers runs. If no config file exists, defaults are used. With the gem in the Gemfile the two merge key by key (Precedence).
Legacy command
rails 'ai:context_for[claude]' # Requires quoting in zsh
rails ai:context:claude # Use this instead (no quoting needed)
CLI Tools
All 35 MCP tools can be run directly from the terminal - no MCP server or AI client needed.
Rake
# Run a tool with arguments
rails 'ai:tool[schema]' table=users detail=full
# List all available tools
rails ai:tool
# JSON envelope output
rails 'ai:tool[schema]' table=users JSON=1
Thor CLI
# Run a tool with arguments
rails-ai-context tool schema --table users --detail full
# List all tools
rails-ai-context tool
# Per-tool help (auto-generated from input_schema)
rails-ai-context tool schema --help
# JSON output
rails-ai-context tool schema --table users --json
Tool name resolution
Short names are resolved automatically:
| You type | Resolves to |
|---|---|
schema |
rails_get_schema |
get_schema |
rails_get_schema |
rails_get_schema |
rails_get_schema |
search_code |
rails_search_code |
analyze_feature |
rails_analyze_feature |
tool_mode configuration
The tool_mode config controls how tool references appear in generated context files:
if defined?(RailsAiContext) && RailsAiContext.respond_to?(:configure)
RailsAiContext.configure do |config|
# :mcp (default) - MCP primary, CLI as fallback
# :cli - CLI only, no MCP server needed
config.tool_mode = :mcp
end
end
:mcp- context files show MCP tool syntax (e.g.rails_get_schema(table: "users")), each example in that form alone. The root file names the CLI fallback once and lists no tool names, since the MCP client lists the tools itself.:cli- context files show CLI syntax (e.g.rails 'ai:tool[schema]' table=users). No MCP server required. Every file follows it: the root files, the split rule files and OpenCode's per-directoryAGENTS.md, whose tools rule files then describe the CLI tools. The root file lists the tool names, since nothing else does.
Every tool count and list in the generated files is the set the server serves: the built-in tools skip_tools leaves, plus custom_tools. In CLI mode the root file's list of commands names a custom tool too; in MCP mode the client lists every tool itself. A workflow step, rule or pointer whose tool is skipped is left out, or said without the tool (with rails_get_context skipped, the model workflow starts from rails_get_model_details), so no file sends the AI to a tool the server does not serve.
The workflow examples name the app's own most connected model, one of its controllers, a template and a partial it renders. An app with none of one gets an obvious placeholder (YourModel, shared/your_partial) rather than a name that reads like the app's.
The tool_mode is selected during rails generate rails_ai_context:install.
MCP Tools - Common Reference
The 21 tools below are the ones worth reading about before you start. Tools Reference carries all 35 with their parameters.
Every tool is read-only and idempotent - they never modify your application or database.
rails_get_schema
Returns database schema: tables, columns, indexes, foreign keys.
Parameters:
| Param | Type | Description |
|---|---|---|
table |
string | Specific table name for full detail. Omit for listing. |
detail |
string | summary / standard (default) / full |
limit |
integer | Max tables to return. Default: 50 (summary), 25 (standard), 10 (full). |
offset |
integer | Skip tables for pagination. Default: 0. |
format |
string | markdown (default) / json. JSON returns the same page of tables keyed by table name, or the single table's own data when table is given. |
Examples:
rails_get_schema()
→ Standard detail, first 25 tables with column names and types
rails_get_schema(detail: "summary")
→ All tables with column and index counts (up to 50)
rails_get_schema(table: "users")
→ Full detail for users table: columns, types, nullable, defaults, indexes, FKs
rails_get_schema(detail: "summary", limit: 20, offset: 40)
→ Tables 41-60 with column counts
rails_get_schema(detail: "full", format: "json")
→ The same page of tables as JSON, with indexes and foreign keys
rails_get_model_details
Returns model details: associations, validations, scopes, enums, callbacks, concerns. Source parsing uses Prism AST. The model heading and each scope carry a confidence tag: [VERIFIED] (confirmed by the booted app, or static literal arguments), [INFERRED] (dynamic expressions) or [STATIC] (read from source without a boot).
Parameters:
| Param | Type | Description |
|---|---|---|
model |
string | Model class name (e.g. User). Case-insensitive. Omit for listing. |
detail |
string | summary / standard (default) / full. Ignored when model is specified. |
limit |
integer | Max models to return when listing. Default: 50. |
offset |
integer | Skip models for pagination. Default: 0. |
Examples:
rails_get_model_details()
→ Standard: all model names with association and validation counts
rails_get_model_details(detail: "summary")
→ Just model names, one per line
rails_get_model_details(model: "User")
→ Full detail: table, associations, validations, enums, scopes, callbacks, concerns, methods
rails_get_model_details(model: "user")
→ Same as above (case-insensitive)
rails_get_model_details(detail: "full")
→ All models with full association lists
rails_get_routes
Returns all routes: HTTP verbs, paths, controller actions, route names.
Parameters:
| Param | Type | Description |
|---|---|---|
controller |
string | Filter by controller name (e.g. users, api/v1/posts). Case-insensitive. |
detail |
string | summary / standard (default) / full |
limit |
integer | Max routes to return. Default: 150 (standard), 200 (full). |
offset |
integer | Skip routes for pagination. Default: 0. |
app_only |
boolean | Leave out the routes Rails' engines and gems draw on their own (Active Storage, Action Mailbox and its conductor, Turbo Native navigation, rails/info, rails/mailers, rails/welcome). The app's own declarations stay, devise_for and the health check included. A controller filter searches every route. Default: true. |
Examples:
rails_get_routes()
→ Standard: routes grouped by controller with verb, path, action
rails_get_routes(detail: "summary")
→ Route counts per controller with verb breakdown
rails_get_routes(controller: "users")
→ All routes for UsersController
rails_get_routes(controller: "posts")
→ Also reaches a namespaced `api/v1/posts`: an exact name first, then the trailing path segments, never a substring
rails_get_routes(detail: "full", limit: 50)
→ Full table with route names, first 50 routes
rails_get_routes(detail: "standard", limit: 20, offset: 100)
→ Routes 101-120
rails_get_controllers
Returns controller details: actions, filters, strong params, concerns. Automatically includes Schema Hints for models referenced in the controller (via Prism AST detection).
Parameters:
| Param | Type | Description |
|---|---|---|
controller |
string | Specific controller name (e.g. UsersController, posts, admin/posts). Case-insensitive, flexible format. |
action |
string | Specific action (e.g. index). Requires controller. Returns source code with applicable filters. |
detail |
string | summary / standard (default) / full. Ignored when controller is specified. |
limit |
integer | Max controllers to return when listing. Default: 50. |
offset |
integer | Skip this many controllers for pagination. Default: 0. |
Examples:
rails_get_controllers()
→ Standard: controller names with action lists
rails_get_controllers(detail: "summary")
→ Controller names with action counts
rails_get_controllers(controller: "UsersController")
→ Full detail: parent class, actions, filters (with only/except), strong params
rails_get_controllers(detail: "full")
→ All controllers with actions, filters, and strong params
rails_get_config
Returns the app's configuration, one section per call. section picks it: app (the default), gems, frontend, api, engines, conventions, autoload, active_support, env, env_config or i18n. Ten sections were tools of their own (rails_get_gems, rails_get_env and the rest); each answers what its tool did, and the old names still work from the CLI and over MCP.
Parameters:
| Param | Type | Description |
|---|---|---|
section |
string | Which section. Default: app. Required when skip_tools turns app off. |
detail |
string | summary / standard (default) / full. Read by frontend, api and env. For env, summary is env var names only, standard groups them by source with external services, full adds per-file locations, Dockerfile vars and credentials keys. |
category |
string | Read by gems: auth, jobs, frontend, api, database, files, testing, deploy, monitoring, admin, pagination, search, forms, server, notifications, validation, utilities, services, payments, all (default). |
environment |
string | Read by env_config: one environment, by exact name. |
locale |
string | Read by i18n: one locale's files and coverage. |
offset, limit |
integer | Read by gems, env_config and i18n. Defaults: 0 and 50. |
A parameter the asked section does not read is named in the answer as ignored.
Returns: for app, cache store, session store, timezone, queue adapter, mailer settings, the app's own middleware classes with their files and the rest of the stack as additions (framework defaults are filtered out), the use and map calls in config.ru, notable initializers, CurrentAttributes classes with the attributes they declare, their defaults and reset hooks. gems groups notable gems by category; conventions lists architecture patterns, directory structure and config files; env lists environment variables grouped by purpose, external services and credentials keys, with no values.
rails_get_config()
→ Cache: redis_cache_store, Session: cookie_store, TZ: UTC, ...
rails_get_config(section: "gems")
→ Auth: devise `4.9.3`, Jobs: sidekiq `7.2.1`, ...
rails_get_config(section: "conventions")
→ Architecture: [MVC, Service objects, Concerns], Patterns: [STI, Polymorphism], ...
rails_get_config(section: "env", detail: "summary")
→ Env var names grouped by category
rails_get_test_info
Returns test infrastructure details. Optionally filter by model or controller to find existing tests.
Parameters:
| Param | Type | Description |
|---|---|---|
model |
string | Show tests for a specific model (e.g. User). Also searches concern test paths (spec/models/concerns/, test/models/concerns/). |
controller |
string | Show tests for a specific controller (e.g. Posts). |
detail |
string | summary / standard (default) / full. |
rails_get_test_info()
→ Framework: rspec, Factories: spec/factories (12 files), CI: .github/workflows/ci.yml
rails_get_test_info(model: "User")
→ Shows spec/models/user_spec.rb test names (summary/standard) or full source (full)
rails_get_stimulus
Returns Stimulus controller details: targets, values, actions, outlets, classes.
Parameters:
| Param | Type | Description |
|---|---|---|
controller |
string | Specific Stimulus controller name (e.g. hello, filter-form). Case-insensitive. |
detail |
string | summary / standard (default) / full |
limit |
integer | Max controllers to return when listing. Default: 50. |
offset |
integer | Skip controllers for pagination. Default: 0. |
Examples:
rails_get_stimulus()
→ Standard: controller names with targets and actions
rails_get_stimulus(detail: "summary")
→ Names with target/action counts
rails_get_stimulus(controller: "filter-form")
→ Full detail: targets, actions, values, outlets, classes, file path
rails_get_stimulus(detail: "full")
→ All controllers with all details
rails_get_view
Returns view template contents, partials, and Stimulus controller references. In standard detail, includes Schema Hints for models inferred from instance variables, and opens with the form builders the views call (with counts) and the ViewComponents they render.
Parameters:
| Param | Type | Description |
|---|---|---|
controller |
string | Filter views by controller name (e.g. posts, comments). Use layouts for layout files. |
path |
string | Specific view path relative to app/views (e.g. posts/index.html.erb). Returns full content. |
detail |
string | summary / standard (default) / full |
Examples:
rails_get_view()
→ Standard: all view files with partial/stimulus refs
rails_get_view(controller: "posts")
→ All templates and partials for PostsController
rails_get_view(path: "posts/index.html.erb")
→ Full template content
rails_get_view(controller: "layouts")
→ Layout files
rails_get_view(controller: "posts", detail: "full")
→ Full template content for all posts views
rails_get_edit_context
Returns just enough context to make a surgical Edit to a file. Returns the target area with line numbers and surrounding code.
Parameters:
| Param | Type | Description |
|---|---|---|
file |
string | Required. File path relative to Rails root (e.g. app/models/post.rb). |
near |
string | Required unless line is given. What to find - a method name, keyword, or string to locate (e.g. scope, def index). |
context_lines |
integer | Lines of context above and below the match. Default: 5. |
line |
integer | Show context_lines either side of this line number instead of searching for near. |
Examples:
rails_get_edit_context(file: "app/models/post.rb", near: "scope")
→ Code around the first scope with line numbers, expanded to full method
rails_get_edit_context(file: "app/controllers/posts_controller.rb", near: "def index")
→ The index action source with surrounding context
rails_validate
Validates syntax of multiple files at once (Ruby, ERB, JavaScript). Optionally runs Rails-aware semantic checks. JavaScript needs node on the PATH; without it a file whose brackets balance is listed as skipped, not as OK.
Parameters:
| Param | Type | Description |
|---|---|---|
files |
array | Required. File paths relative to Rails root (e.g. ["app/models/post.rb", "app/views/posts/index.html.erb"]). |
level |
string | syntax (default) - check syntax only (fast). rails - syntax + semantic checks (partial existence, route helpers, column references, strong params vs schema, callback methods, route-action consistency, has_many dependent, FK indexes, Stimulus controllers). |
Examples:
rails_validate(files: ["app/models/post.rb"])
→ ✓ app/models/post.rb - syntax OK
rails_validate(files: ["app/models/post.rb", "app/controllers/posts_controller.rb", "app/views/posts/index.html.erb"])
→ Checks all three files, reports pass/fail for each
rails_validate(files: ["app/models/post.rb"], level: "rails")
→ Syntax check + semantic warnings (e.g. validates :nonexistent_column, has_many without :dependent)
rails_validate(files: ["app/views/posts/index.html.erb"], level: "rails")
→ Syntax check + partial existence, route helper validity, Stimulus controller existence
rails_search_code
Ripgrep-powered regex search across the codebase.
Parameters:
| Param | Type | Description |
|---|---|---|
pattern |
string | Required. Regex pattern or method name to search for. With definition or class, a plain method or constant name matches literally (valid?), anything else as a regex (generate_.*). |
path |
string | Subdirectory to search in (e.g. app/models, config). Default: entire app. |
file_type |
string | Filter by file extension (e.g. rb, erb, js). Alphanumeric only. |
match_type |
string | any (default), definition (def lines whose method name contains the pattern), class (class/module lines whose name contains it), call (call sites only), trace (full picture - definition with class context + source code + internal calls + sibling methods + callers with route chain + test coverage separated). |
exact_match |
boolean | Match the pattern literally, whole-word where its edges are word characters. def reblog? does not match def reblog. Default: false. |
exclude_tests |
boolean | Exclude test/spec/features directories. Default: false. |
group_by_file |
boolean | Group results by file with match counts. Default: false. |
offset |
integer | Skip this many lines for pagination. Default: 0. |
limit |
integer | Max lines to return; the default is sized in matches. |
context_lines |
integer | Lines of context before and after each match (like grep -C). Default: 2, max: 5. |
Smart result limiting, sized in matches: under 10 shows all, 10-100 shows half, over 100 caps at 100. offset and limit count emitted lines, so a search with context returns more lines than matches. The header says how many matches were found, how many the page shows, and whether the line cap was reached. The cap always holds the first match and the context before it, so a max_search_results below context_lines + 1 is raised to that. Once it names the cap, the count covers only the lines it scanned, so it is written N+.
Examples:
rails_search_code(pattern: "publishable?", match_type: "trace")
→ FULL PICTURE: definition with class context + source code + internal calls
+ sibling methods + app callers with route chain + test coverage (separated)
rails_search_code(pattern: "create", match_type: "definition")
→ Only def lines whose name contains `create`: `def create`, `def self.create`,
`def recreate`; add exact_match: true for `def create` alone
rails_search_code(pattern: "publishable", match_type: "call")
→ Only call sites (excludes the definition)
rails_search_code(pattern: "Controller", match_type: "class")
→ All class/module definitions matching *Controller
rails_search_code(pattern: "has_many", group_by_file: true)
→ Results grouped by file with match counts
rails_search_code(pattern: "post", exclude_tests: true)
→ Skip test/spec directories
rails_search_code(pattern: "generate_.*", match_type: "definition")
→ Only def lines whose name matches the regex (skips method calls)
rails_search_code(pattern: "\\w+Job", match_type: "class")
→ Only class/module definitions whose name matches the regex
Security: Uses Open3.capture3 with array arguments (no shell injection). Validates file_type. Blocks path traversal. Respects excluded_paths and sensitive_patterns config on both backends, and the Ruby fallback reads the ignore files ripgrep reads and ranks them the way ripgrep does: .rgignore over .ignore over .gitignore (each scoped to its own directory) over .git/info/exclude over the global excludes file, the file type deciding before depth, which breaks ties only within one type; .ignore and .rgignore apply outside a git repository too, and a directory the rules ignore is never entered. As ripgrep does, the fallback also reads the ignore files of every directory above the app, the git ones only as far up as the nearest .git (a file for a worktree or submodule), so an app nested in a larger repository gets that repository's rules and a repository nested in the app stops the app's .gitignore. Patterns match case-sensitively, symlinks are not followed but for a directory linked in from the app's git repository, which both search under the app's name for it, and a file with a NUL byte in its first 64 KiB is skipped unread, all as in ripgrep, so the two return the same set.
rails_analyze_feature
Full-stack feature analysis: models, controllers, routes, services, jobs, views, Stimulus controllers, tests, related models, concerns, callbacks, channels, mailers, and environment dependencies in one call.
Parameters:
| Param | Type | Description |
|---|---|---|
feature |
string | Required. Feature keyword to search for (e.g. authentication, User, payments, orders). Case-insensitive partial match across models, controllers, and routes. |
Examples:
rails_analyze_feature(feature: "authentication")
→ Models, controllers, and routes matching "authentication"
rails_analyze_feature(feature: "User")
→ User model with schema columns, associations, validations, scopes;
UsersController with actions and filters;
all user routes with verbs and paths
rails_analyze_feature(feature: "payments")
→ Cross-cutting view: Payment model + PaymentsController + payment routes
rails_analyze_feature(feature: "orders")
→ Everything related to orders across all layers
Returns: Markdown with sections for Models (with columns, associations, validations, scopes, enums), Controllers (with actions and filters), Routes, Services (with their public methods and the files that call them), Jobs and Sidekiq workers (with queue/retry), Views (with partials and Stimulus refs), Stimulus controllers (with targets/values/actions), Tests (with counts), Related models, Concerns, Callbacks, Channels, Mailers, and Environment dependencies. Each section shows match counts.
rails_security_scan
Runs Brakeman static security analysis on the Rails app. Detects SQL injection, XSS, mass assignment, command injection, and other vulnerabilities. Uses the app's brakeman gem, or a brakeman gem installed for the same Ruby when the bundle has none. Returns installation instructions when neither is there.
Parameters:
| Param | Type | Description |
|---|---|---|
files |
array | Filter results to specific files (e.g. ["app/controllers/users_controller.rb"]). Omit to scan entire app. |
confidence |
string | Minimum confidence: high, medium, weak (default) |
checks |
array | Run only specific checks (e.g. ["CheckSQL", "CheckXSS"]) |
detail |
string | summary (counts only), standard (file/line + message, default), full (+ code snippets + CWE + remediation links) |
Examples:
rails_security_scan()
→ All warnings across the entire app, sorted by confidence
rails_security_scan(files: ["app/controllers/users_controller.rb"], confidence: "high")
→ Only high-confidence warnings in the specified controller
rails_security_scan(detail: "full", checks: ["CheckSQL"])
→ Full detail with code snippets, CWE IDs, and remediation links for SQL injection only
Returns: Security warnings grouped by type with file locations, confidence levels, and messages. Full detail includes offending code snippets, CWE identifiers, and links to Brakeman documentation for each warning type.
rails_get_concern
Get ActiveSupport::Concern details: public methods, included modules, and which models/controllers include it. Specify a name for full detail, or omit to list all concerns. Filter by type to narrow to model or controller concerns.
Parameters:
| Param | Type | Description |
|---|---|---|
name |
string | Concern module name (e.g. Searchable, Authenticatable). Omit to list all concerns. |
type |
string | Filter by concern type, the name the listing's section headings print: model, controller, mailer, the root a concern outside every concerns directory lives in (service, lib), other, or all (default). |
detail |
string | summary / standard (default) / full. Only read when name is given: full adds each method's source code, summary and standard both return method signatures. The listing is the same at every level. |
Examples:
rails_get_concern()
→ Lists all model and controller concerns with method counts
rails_get_concern(name: "Searchable")
→ Full detail: public methods, class methods, macros, callbacks, and which models include it
rails_get_concern(type: "model")
→ Lists only model concerns from app/models/concerns/
Returns: Concern listing or full detail including file path, line count, included/extended modules (a conditional include with its condition), macros and DSL usage (helper_method included), public methods, class methods, private methods, callbacks, and a list of models or controllers that include the concern. The listing counts private methods apart from public ones. Cross-references to related model/controller tools.
rails_get_callbacks
Get ActiveRecord model callbacks grouped by type, in Rails event order: before/after/around for validation, save, create, update, destroy. Specify a model for one model's callbacks, or omit to see all models with their callbacks.
Parameters:
| Param | Type | Description |
|---|---|---|
model |
string | Model class name (e.g. User, Post). Omit to see all models with their callbacks. |
detail |
string | summary / standard (default) / full. summary: model names + callback counts. standard: callbacks by type in Rails event order. full: callbacks with method source code. |
Examples:
rails_get_callbacks(model: "User")
→ User's callbacks by type, in Rails event order: before_validation, after_validation, before_save, etc.
rails_get_callbacks(detail: "summary")
→ All models with callback counts, sorted by most callbacks
rails_get_callbacks(model: "Order", detail: "full")
→ Order's callbacks with the actual method source code for each callback
Returns: Callbacks grouped by type, in Rails event order. Includes
concern-provided callbacks, with their bodies read from the concern file.
Within one type the order is the order Rails runs them, base classes first, a
before_ or around_ callback with prepend: true first, and
after_commit/after_rollback last declared first unless the app runs them in
order (load_defaults 7.1). A method declared again shows once with the later
declaration's conditions. A block or lambda callback shows its declaration at
detail: "full", and turbo-rails' broadcast macros (broadcasts_refreshes,
broadcasts_to and the rest) are listed as the commit callbacks they declare.
rails_get_helper_methods
Get Rails helper modules: method signatures, framework helpers in use, and which views call each helper. Specify a helper for full detail, or omit to list all helpers with method counts.
Parameters:
| Param | Type | Description |
|---|---|---|
helper |
string | Helper module name (e.g. ApplicationHelper, UsersHelper). Omit to list all helpers. |
detail |
string | summary / standard (default) / full. summary: names + method counts. standard: names + method signatures. full: method signatures + view cross-references + framework helpers. |
limit |
integer | Max helpers to return. Default: 50. |
offset |
integer | Skip this many helpers for pagination. Default: 0. |
Examples:
rails_get_helper_methods()
→ All helpers with method signatures (standard detail)
rails_get_helper_methods(helper: "ApplicationHelper")
→ Full detail: method signatures, included modules
rails_get_helper_methods(detail: "full")
→ All helpers with method signatures + detected framework helpers (Devise, Pagy, Turbo, etc.)
Returns: Helper module listing or full detail including file path, method signatures, included modules, and (at full detail) which views reference each helper method. Detects usage of framework helpers from Devise, Pagy, Turbo, Pundit, CanCanCan, Kaminari, SimpleForm, and others.
rails_get_service_pattern
Analyze service objects in app/services/, app/interactions/ and app/interactors/: patterns, interfaces, dependencies, and side effects. Specify a service for full detail, or omit to detect the common pattern and list all services.
Parameters:
| Param | Type | Description |
|---|---|---|
service |
string | Service class name or filename (e.g. CreateOrder, create_order). Omit to list all services with pattern detection. |
detail |
string | summary / standard (default) / full. summary: names only. standard: names + method signatures + line counts. full: everything including side effects, error handling, and callers. |
Examples:
rails_get_service_pattern()
→ All services with detected common pattern (e.g. "initialize + call instance method")
rails_get_service_pattern(service: "CreateOrder")
→ Full detail: initialize params, public methods, dependencies, error handling, side effects, callers
rails_get_service_pattern(detail: "full")
→ All services with methods, initialize params, side effects, and rescue blocks
Returns: Service listing with common pattern detection (initialize+call, self.call, Result objects) or full detail including file path, initialize parameters, public methods, dependencies (other classes called), error handling (rescue blocks), side effects (database writes, email delivery, job enqueues, HTTP requests, Turbo broadcasts), and a list of files that call the service. A base class other services inherit from is named above the listing and left out of the service count; asking for it by name still answers. When the service directories hold more Ruby files than the listing counts, one line says how many were left out and of which kind.
rails_get_job_pattern
Analyze background jobs in app/jobs/, app/workers/ and app/sidekiq/: queues, retries, perform signatures, guards, and what they call. Specify a job for full detail, or omit to list all jobs with queue names and retry config.
Parameters:
| Param | Type | Description |
|---|---|---|
job |
string | Job class name or filename (e.g. SendWelcomeEmailJob, send_welcome_email). Omit to list all jobs. |
detail |
string | summary / standard (default) / full. summary: names + queues. standard: names + queues + retries + what they call. full: everything including guards, broadcasts, schedules, and enqueuers. |
Examples:
rails_get_job_pattern()
→ All jobs with queue summary and retry config
rails_get_job_pattern(job: "SendWelcomeEmailJob")
→ Full detail: queue, retry config, perform signature, guard clauses, dependencies, broadcasts, schedule, side effects, enqueuers
rails_get_job_pattern(detail: "full")
→ All jobs with guards, broadcasts, side effects, and schedules
Returns: Job listing with queue breakdown or full detail including queue name, retry/discard configuration (retry_on, discard_on, Sidekiq options), perform method signature, guard clauses (early returns), dependencies (classes called), Turbo broadcasts, cron/recurring schedule (from sidekiq.yml or config files), side effects, and a list of files that enqueue the job.
rails_get_partial_interface
Analyze a partial's interface: local variables it expects, where it's rendered from, and what methods are called on each local. Use when rendering a partial, understanding what locals to pass, or refactoring partial dependencies.
Parameters:
| Param | Type | Description |
|---|---|---|
partial |
string | Required. Partial path relative to app/views (e.g. shared/status_badge, users/form). The leading underscore is optional. |
detail |
string | summary / standard (default) / full. summary: locals list + usage count. standard: locals + usage examples from codebase. full: locals + usage + full partial source. |
Examples:
rails_get_partial_interface(partial: "shared/status_badge")
→ Local variables, method calls on each local, and all render sites with locals passed
rails_get_partial_interface(partial: "users/form", detail: "summary")
→ Local variable names + number of render sites
rails_get_partial_interface(partial: "shared/card", detail: "full")
→ Full detail: locals, method calls, render sites with code snippets, and full partial source
Returns: Partial interface including declared locals (Rails 7.1+ magic comment), detected local variable references, method calls on each local, and render sites with file/line and locals passed. Supports underscore-prefixed and non-prefixed names. Full detail includes the complete partial source code.
rails_get_turbo_map
Map Turbo Streams and Frames across the app: model broadcasts, channel subscriptions, frame tags, and DOM target mismatches. Filter by stream or controller name.
Parameters:
| Param | Type | Description |
|---|---|---|
detail |
string | summary / standard (default) / full. summary: count of streams, frames, model broadcasts. standard: each stream with source to target. full: everything including inline template refs and DOM IDs. |
stream |
string | Filter by stream/channel name (e.g. notifications, messages). Shows only broadcasts and subscriptions for this stream. |
controller |
string | Filter by controller name (e.g. messages, comments). Shows Turbo usage in that controller's views and actions. |
Examples:
rails_get_turbo_map()
→ Model broadcasts, explicit broadcasts, stream subscriptions, Turbo Frames, and mismatch warnings
rails_get_turbo_map(stream: "notifications")
→ Only broadcasts and subscriptions for the "notifications" stream
rails_get_turbo_map(controller: "messages", detail: "full")
→ Full Turbo usage in messages controller with DOM IDs, stream wiring map, and mismatch warnings
Returns: Turbo Streams and Frames mapped across the app. Model broadcasts (via broadcasts, broadcasts_to, broadcasts_refreshes), explicit broadcasts (broadcast_replace_to, broadcast_append_to, etc.), stream subscriptions (turbo_stream_from in views), and Turbo Frames (turbo_frame_tag with IDs and src). Full detail includes a stream wiring map connecting broadcasters to subscribers, and warnings for broadcasts without subscribers or subscriptions without broadcasters.
rails_get_context
Get cross-layer context in a single call - combines schema, model, controller, routes, views, stimulus, and tests. Automatically includes Schema Hints for models referenced in controller/view code. Use when you need full context for implementing a feature or modifying an action.
Parameters:
| Param | Type | Description |
|---|---|---|
controller |
string | Controller name (e.g. PostsController). Returns action source, filters, strong params, routes, views. |
action |
string | Specific action name (e.g. create). Requires controller. Returns full action context. |
model |
string | Model name (e.g. Post). Returns schema, associations, validations, scopes, callbacks, tests. |
feature |
string | Feature keyword (e.g. post). Like analyze_feature but includes schema columns and scope bodies. |
include |
array | Extra context to append in any mode: stimulus, turbo, services, jobs, conventions, helpers, env, callbacks. |
Examples:
rails_get_context(controller: "PostsController", action: "create")
→ Controller action source + model details + routes + views - everything for that action
rails_get_context(model: "User")
→ Model details + schema columns + the names of its tests
rails_get_context(feature: "orders")
→ Full-stack feature analysis including schema columns and scope bodies
Returns: Combined context from multiple tools in a single response. For controller+action: controller source with filters, inferred model details, matching routes, and view templates. For model: model details with associations/validations/scopes, schema columns with types, and the names of the tests in its test file. For feature: delegates to full-stack feature analysis.
Detail Level Summary
All tools that support detail use these three levels. Default limits vary by tool - schema defaults shown below:
| Level | What it returns | Schema default limit | Best for |
|---|---|---|---|
summary |
Names + counts | 50 | Getting the landscape, understanding what exists |
standard |
Names + key details | 25 | Working context, column types, action names |
full |
Everything | 10 | Deep inspection, indexes, FKs, constraints |
Other tools default to higher limits (e.g. models/controllers/stimulus: 50 for all levels, routes: 150/200).
Recommended Workflow
- Start with
detail:"summary"to see what exists - Filter by name (
table:,model:,controller:) for the item you need - Use
detail:"full"only when you need indexes, foreign keys, or constraints - Paginate with
limitandoffsetfor large result sets
MCP Resources
In addition to tools, the gem registers static MCP resources that AI clients can read directly:
| Resource URI | Description |
|---|---|
rails://schema |
Full database schema (JSON) |
rails://routes |
All routes (JSON) |
rails://conventions |
Detected patterns and architecture (JSON) |
rails://gems |
Notable gems with categories, plus declared_ruby_version and which of the lockfile, Gemfile, .ruby-version, .tool-versions or a mise config file answered (JSON) |
rails://controllers |
All controllers with actions and filters (JSON) |
rails://config |
Application configuration (JSON) |
rails://tests |
Test infrastructure details (JSON) |
rails://migrations |
Migration history and statistics (JSON) |
rails://engines |
Mounted engines with paths and descriptions (JSON) |
rails-ai-context://models/{name} |
Per-model details (resource template) |
The legacy rails://models/{name} form is still accepted.
Dynamic Resource Templates (VFS)
Live resources answered from the context the tools share, checked against the files on every request and introspected again after any edit:
| Resource Template | Description |
|---|---|
rails-ai-context://controllers/{name} |
Controller details with actions, filters, strong params |
rails-ai-context://controllers/{name}/{action} |
Specific action source code and applicable filters |
rails-ai-context://views/{path} |
View template content (path traversal protected) |
rails-ai-context://routes/{controller} |
Live route map, filtered by controller |
MCP Server Setup
MCP Registry
This server is listed on the official MCP Registry as io.github.crisnahine/rails-ai-context.
# Search for it
curl "https://registry.modelcontextprotocol.io/v0.1/servers?search=rails-ai-context"
Per-tool MCP config files (recommended)
The install generator (or rails-ai-context init) creates per-tool MCP config files based on your selected AI tools:
| AI Tool | Config File | Root Key | Format |
|---|---|---|---|
| Claude Code | .mcp.json |
mcpServers |
JSON |
| Cursor | .cursor/mcp.json |
mcpServers |
JSON |
| GitHub Copilot (VS Code) | .vscode/mcp.json |
servers |
JSON |
| GitHub Copilot CLI | .github/mcp.json |
mcpServers |
JSON |
| OpenCode | opencode.json |
mcp |
JSON |
| Codex CLI | .codex/config.toml |
[mcp_servers] |
TOML |
Each file is merge-safe - only the rails-ai-context entries are managed, other servers are preserved. When the gem is not in the app's Gemfile.lock (standalone install) the entry runs rails-ai-context serve with no bundle exec.
On Windows every entry starts the server through cmd /d /c: "command": "cmd", "args": ["/d", "/c", "bundle", "exec", "rails-ai-context", "serve"] (OpenCode: "command": ["cmd", "/d", "/c", ...]; Codex: command = "cmd"). A gem's executables there are batch files (bundle.bat, rails-ai-context.bat), which Claude Code, Codex and the other clients that start a server without a shell do not run, and /d keeps the registry's AutoRun commands from printing ahead of the server's first message. An entry written on Windows does not start on macOS or Linux, and one written there may not start on Windows: doctor names either, and running the install again rewrites it for the machine it runs on. A team on both keeps the MCP configs out of git, or runs the install on each machine.
A folder of apps gets one entry per app instead, rails-ai-context-<app folder>, each pointed at its app with --app-path and announcing its app first through RAILS_AI_CONTEXT_SERVER_NAME; see init for the shape each AI tool gets.
Example: .mcp.json (Claude Code)
{
"mcpServers": {
"rails-ai-context": {
"command": "bundle",
"args": ["exec", "rails-ai-context", "serve"]
}
}
}
Example: .codex/config.toml (Codex CLI)
[mcp_servers.rails-ai-context]
command = "bundle"
args = ["exec", "rails-ai-context", "serve"]
env_vars = ["GEM_HOME", "GEM_PATH", "GEM_ROOT", "RUBY_VERSION", "BUNDLE_PATH"]
startup_timeout_sec = 30.0
Why
env_vars? Codex starts an MCP server with a cleared environment that still keepsPATH,HOMEand a few more.env_varspasses the other variables a Ruby setup needs from the shell Codex was started in: rvm and chruby set them besidePATH; rbenv, asdf and mise need onlyPATH.startup_timeout_seccovers the app's boot, since Codex waited only 10 s for a server before 0.120. A Codex table an earlier release wrote with this machine'sPATHandGEM_HOMEsaved in anenvtable is replaced the next time the install runs.
Each AI tool finds its own config file when it opens the project, then holds the server back until you approve it once: approve it in Claude Code, turn it on in Cursor, trust the folder in VS Code and Codex CLI, restart OpenCode. The install's summary names the step for each tool you picked (AI tool setup).
Claude Code
Read from .mcp.json once you approve the server. Or add manually:
# In-Gemfile
claude mcp add rails-ai-context -- bundle exec rails ai:serve
# Standalone
claude mcp add rails-ai-context -- rails-ai-context serve
# On Windows, through cmd /d /c
claude mcp add rails-ai-context -- cmd /d /c bundle exec rails-ai-context serve
Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"rails-ai-context": {
"command": "bundle",
"args": ["exec", "rails-ai-context", "serve"],
"cwd": "/path/to/your/rails/app"
}
}
}
Or for standalone: replace "command": "bundle" / "args": ["exec", "rails-ai-context", "serve"] with "command": "rails-ai-context" / "args": ["serve"]. On Windows, start either through cmd /d /c: "command": "cmd", with "/d", "/c" ahead of the rest of the args.
Cursor
Read from .cursor/mcp.json once you turn the server on. Or add manually:
{
"mcpServers": {
"rails-ai-context": {
"command": "bundle",
"args": ["exec", "rails-ai-context", "serve"],
"cwd": "/path/to/your/rails/app"
}
}
}
For standalone: use "command": "rails-ai-context" / "args": ["serve"] instead.
HTTP transport
For browser-based or remote AI clients:
rails ai:serve_http
# Starts at http://127.0.0.1:6029/mcp
Or auto-mount inside your Rails app (no separate process):
if defined?(RailsAiContext) && RailsAiContext.respond_to?(:configure)
RailsAiContext.configure do |config|
config.auto_mount = true
config.http_path = "/mcp" # default
end
end
The endpoint is then served by your app's own server, on its address and port; http_bind and http_port configure only the standalone process.
Both transports are read-only - they expose the same 35 tools and never modify your app.
Controller Transport (Alternative)
For tighter Rails integration (authentication, routing, middleware stack), mount the engine instead of using Rack middleware:
# config/routes.rb
mount RailsAiContext::Engine, at: "/mcp" if defined?(RailsAiContext::Engine)
The if keeps the routes file loading wherever the gem is not: in production, where Bundler skips the :development group, and after the gem is removed. An unguarded mount raises uninitialized constant RailsAiContext::Engine there, and the app does not boot.
This provides a native Rails controller (RailsAiContext::McpController) that delegates to the Streamable HTTP transport. Outside development and test (production, staging) it refuses every request with a 403, as auto_mount does, unless you set config.allow_http_in_production = true; see Security.
The controller runs each call on the request's own thread and sends the answer whole, which keeps calls answering while the app reloads code in development. A custom tool's progress or log notifications therefore arrive together with its answer, and a request a tool makes of the client mid-call (sampling, elicitation, roots) fails at once; stdio and the standalone HTTP server deliver both as they are sent (Setup).
Configuration - All Options
# config/initializers/rails_ai_context.rb
if defined?(RailsAiContext) && RailsAiContext.respond_to?(:configure)
RailsAiContext.configure do |config|
# --- Introspectors ---
# Presets: :full (40 introspectors, default) or :standard (17)
config.preset = :full
# Cherry-pick on top of a preset
config.introspectors += %i[views turbo auth api]
# --- Context files ---
# Context mode: :compact (default) or :full
config.context_mode = :compact
# Max non-blank lines for the root file in compact mode
config.claude_max_lines = 150
# Output directory for context files (default: Rails.root)
# config.output_dir = "/custom/path"
# --- MCP tools ---
# Tool mode: :mcp (MCP primary + CLI fallback) or :cli (CLI only)
config.tool_mode = :mcp
# Max response size for tool results (safety net)
config.max_tool_response_chars = 200_000
# Cache TTL for introspection results (seconds)
config.cache_ttl = 60
# Additional MCP tool classes to register alongside built-in tools
# config.custom_tools = [MyApp::Tools::CustomTool]
# Exclude specific built-in tools (e.g. if you don't use Brakeman)
# config.skip_tools = %w[rails_security_scan]
# --- Exclusions ---
# Models to skip during introspection
config.excluded_models += %w[AdminUser InternalAuditLog]
# Paths to exclude from code search
config.excluded_paths += %w[vendor/bundle]
# Sensitive file patterns blocked from search and read tools
# config.sensitive_patterns += %w[config/my_secret.yml]
# Controllers hidden from listings (e.g. Devise internals)
# config.excluded_controllers += %w[MyInternalController]
# Route prefixes hidden with app_only (e.g. admin frameworks)
# config.excluded_route_prefixes += %w[admin/]
# Framework association names hidden from model output (ActiveStorage, ActionText, etc.)
# config.excluded_association_names += %w[my_custom_framework_assoc]
# Regex patterns for concerns to hide from model output
# config.excluded_concerns += [/MyInternal::/]
# Framework filter names hidden from controller output
# config.excluded_filters += %w[my_internal_filter]
# Default middleware hidden from config output
# config.excluded_middleware += %w[MyMiddleware]
# --- File size limits ---
# Per-file read limit for tools (default: 5MB)
# config.max_file_size = 5_000_000
# Test file read limit (default: 1MB)
# config.max_test_file_size = 1_000_000
# schema.rb / structure.sql parse limit (default: 10MB)
# config.max_schema_file_size = 10_000_000
# app/views size the doctor warns past - not a read cap (default: 10MB)
# config.max_view_total_size = 10_000_000
# Accepted and stored; no check reads it (default: 1MB)
# config.max_view_file_size = 1_000_000
# Max search results per call (default: 200)
# config.max_search_results = 200
# Max files per validate call (default: 50)
# config.max_validate_files = 50
# --- Search and file discovery ---
# Narrow the Ruby fallback to these extensions (unset: every file, as ripgrep)
# config.search_extensions = %w[rb js erb yml yaml json ts tsx vue svelte haml slim]
# Where to look for concern source files. Left unset, every
# app/concerns and app/*/concerns directory is discovered. Setting this replaces
# that list, so it can narrow as well as reach outside app/.
# config.concern_paths = %w[app/models/concerns lib/concerns]
# --- Live reload ---
# Auto-invalidate MCP tool caches on file changes
# :auto - enable if `listen` gem is available (default)
# true - enable, raise if `listen` is missing
# false - disable entirely
config.live_reload = :auto
config.live_reload_debounce = 1.5 # seconds
# --- HTTP MCP endpoint ---
# Auto-mount Rack middleware for HTTP MCP
config.auto_mount = false
# Let the mounted engine and auto_mount answer in production
config.allow_http_in_production = false
config.http_path = "/mcp"
config.http_bind = "127.0.0.1"
config.http_port = 6029
end
end
Options reference
| Option | Type | Default | Description |
|---|---|---|---|
preset |
Symbol | :full |
Introspector preset (:full or :standard) |
introspectors |
Array | 40 (full preset) | Which introspectors to run |
context_mode |
Symbol | :compact |
:compact or :full |
claude_max_lines |
Integer | 150 |
Budget for the non-blank lines of the compact root file's gem-managed block, the <!-- BEGIN/END rails-ai-context --> markers included, beside its 12,000 bytes. Over budget, the data sections (Stack, Key models, Gems, Architecture) are cut from the bottom, down to none; the title and the Commands, Warnings, Rules and Tools sections are never cut, so they set the smallest file a budget can give (about 70 lines with the anti-hallucination protocol) |
max_tool_response_chars |
Integer | 200_000 |
Safety cap for MCP tool responses and resource payloads |
cache_ttl |
Integer | 60 |
Cache TTL in seconds for introspection results |
custom_tools |
Array | [] |
Additional MCP tool classes to register alongside built-in tools |
skip_tools |
Array | [] |
Built-in tool names to exclude (e.g. %w[rails_security_scan]). A custom tool with a skipped built-in's name takes its place, rails_get_config with its sections included |
tool_mode |
Symbol | :mcp |
:mcp (MCP primary + CLI fallback) or :cli (CLI only, no MCP server needed) |
ai_tools |
Array | nil (all) |
AI tools to generate context for: %i[claude cursor copilot opencode codex]. Selected during install. |
excluded_models |
Array | internal Rails models | Models to skip |
excluded_paths |
Array | node_modules tmp log vendor .git doc docs |
Paths excluded from code search |
sensitive_patterns |
Array | .env, .key, .pem, credentials |
File patterns blocked from search and read tools |
output_dir |
String | nil (Rails.root) |
Where to write context files. OpenCode's app/models/AGENTS.md and app/controllers/AGENTS.md are written only where that directory exists under it |
auto_mount |
Boolean | false |
Auto-mount HTTP MCP endpoint |
allow_http_in_production |
Boolean | false |
Let the mounted engine and auto_mount answer in production and every other environment but development and test. Off, they refuse there with a 403. See Security |
http_path |
String | "/mcp" |
HTTP endpoint path (auto_mount and the standalone server) |
http_bind |
String | "127.0.0.1" |
Address the standalone HTTP server binds. Another address still answers only a loopback Host header; see CONFIGURATION |
http_port |
Integer | 6029 |
Port of the standalone HTTP server |
live_reload |
Symbol/Boolean | :auto |
:auto, true, or false - enable MCP live reload |
live_reload_debounce |
Float | 1.5 |
Debounce interval in seconds for live reload |
server_name |
String | "rails-ai-context" |
The MCP server name the server announces. When it is left at the default, the RAILS_AI_CONTEXT_SERVER_NAME environment variable takes its place for one process, which is how a workspace's entries announce their app |
server_version |
String | gem version | MCP server version. Read-only, there is no setter |
generate_root_files |
Boolean | true |
Set false to generate split rules only: no CLAUDE.md, AGENTS.md or copilot-instructions.md, and the overview and tools rules are written in their place (.ai-context.json is still written) |
anti_hallucination_rules |
Boolean | true |
Embed 6-rule Anti-Hallucination Protocol in generated context files - set false to skip |
report_issue_line |
Boolean | true |
End every tool answer with one line asking the AI to offer you a GitHub issue when rails-ai-context answered wrong - set false to leave it out |
hydration_enabled |
Boolean | true |
Inject schema hints into controller/view tool responses |
hydration_max_hints |
Integer | 5 |
Max schema hints per tool response |
max_file_size |
Integer | 5_000_000 |
Per-file read limit for tools (5MB) |
max_test_file_size |
Integer | 1_000_000 |
Test file read limit (1MB) |
max_schema_file_size |
Integer | 10_000_000 |
schema.rb / structure.sql parse limit (10MB) |
max_view_total_size |
Integer | 10_000_000 |
Doctor threshold: app/views above this warns (10MB). Not a read cap |
max_view_file_size |
Integer | 1_000_000 |
Accepted and stored; no check reads it (1MB). Not a read cap |
max_search_results |
Integer | 200 |
Max lines a search may emit per call, matches and context together |
max_validate_files |
Integer | 50 |
Max files per validate call |
excluded_controllers |
Array | DeviseController, etc. |
Controller classes hidden from listings |
excluded_route_prefixes |
Array | action_mailbox/, active_storage/, rails/conductor/, rails/info, rails/mailers, rails/welcome, turbo/ |
Route controller prefixes hidden with app_only: the routes Rails' engines and gems draw on their own |
excluded_association_names |
Array | 7 framework associations | Framework association names hidden from model output |
excluded_concerns |
Array of Regex or String | framework regex patterns | Patterns for concerns to hide. A YAML list replaces the framework defaults; the initializer's += adds to them |
excluded_filters |
Array | verify_authenticity_token, etc. |
Framework filter names hidden from controller output |
excluded_middleware |
Array | standard Rails middleware | Default middleware hidden from config output |
search_extensions |
Array | nil |
Narrows the Ruby fallback to these extensions. Unset, it searches every non-hidden, non-binary file, as ripgrep does |
concern_paths |
Array | nil (discovers app/concerns and app/*/concerns) |
Where to look for concern source files. Setting it replaces discovery |
context_files |
Boolean | true |
Set false for an MCP-only install: no CLAUDE.md, AGENTS.md, rules files or .ai-context.json are written |
frontend_paths |
Array | nil (auto-detected) |
Frontend directories, e.g. ["app/frontend", "../web-client"]. One outside the app root is read for manifests only |
extra_app_paths |
Array | [] |
More app-root-relative directories that hold Rails app code. Each one's app/models, app/controllers and app/views are scanned |
query_timeout |
Number | 5 |
rails_query statement timeout in seconds, a positive number |
query_row_limit |
Integer | 100 |
Max rows rails_query returns (1 to 1000) |
query_redacted_columns |
Array | password_digest, encrypted_password, tokens, etc. |
Column names rails_query refuses: a query naming one is rejected before it runs, and a returned column of that name comes back [FILTERED] |
query_allowed_columns |
Array | [] |
Column names to exempt from the built-in secret column names. It does not release an encrypts column |
allow_query_in_production |
Boolean | false |
Allow rails_query in production |
log_lines |
Integer | 50 |
Default number of lines rails_read_logs tails |
instrumentation_include_arguments |
Boolean | false |
Forward raw tool arguments in ActiveSupport::Notifications events |
Root file generation
By default, rails ai:context generates root files (CLAUDE.md, AGENTS.md, etc.) alongside split rules.
Section markers: Generated content is wrapped in <!-- BEGIN rails-ai-context --> / <!-- END rails-ai-context --> markers. If you add custom notes above or below the markers, they will be preserved when you re-run rails ai:context.
Skip root files: If you prefer to maintain root files yourself and only want split rules (.claude/rules/, .cursor/rules/, .github/instructions/):
if defined?(RailsAiContext) && RailsAiContext.respond_to?(:configure)
RailsAiContext.configure do |config|
config.generate_root_files = false
end
end
With root files off, the Claude Code, Cursor and Copilot rule sets each get an app overview (rails-context.md, rails-project.mdc, rails-context.instructions.md) and the tools guide (rails-mcp-tools.md, rails-mcp-tools.mdc, rails-mcp-tools.instructions.md) in the root file's place, each loaded in every session. With root files on, a run removes those six, since the root file states them. OpenCode and Codex have no overview outside AGENTS.md: their split files hold only the model and controller listings.
Introspectors - Full List
Standard preset (17 introspectors)
Core Rails structure only. Use config.preset = :standard for a lighter footprint.
| Introspector | What it discovers |
|---|---|
schema |
Tables, columns, types, indexes, foreign keys, primary keys. Falls back to db/schema.rb parsing when no DB connected. |
models |
Associations, validations, scopes, enums, callbacks, concerns, instance methods, class methods. Source-level macros via Prism AST (single-pass, 8 listeners): has_secure_password, encrypts, normalizes, delegate, serialize, store, generates_token_for, has_one_attached, has_many_attached, has_rich_text, broadcasts, broadcasts_to, broadcasts_refreshes, broadcasts_refreshes_to. Every result tagged [VERIFIED] or [INFERRED]. |
routes |
All routes with HTTP verbs, paths, controller actions, route names, API namespaces, mounted engines. |
jobs |
ActiveJob classes with queue names. Mailers with action methods. Action Cable channels. |
gems |
127 notable gems categorized: auth, jobs, frontend, api, database, files, testing, deploy, monitoring, admin, pagination, search, forms, server, notifications, validation, utilities, services, payments. |
conventions |
Architecture patterns (MVC, service objects, STI, polymorphism, etc.), directory structure with file counts, config files, detected patterns. |
controllers |
Actions, filters (before/after/around with only/except), strong params methods, parent class, API controller detection, concerns. |
tests |
Test framework (rspec/minitest), factories/fixtures with locations and counts, system tests, CI config files, coverage tool, test helpers, VCR cassettes. |
migrations |
Total count, schema version, pending migrations, recent migration history with detected actions (create_table, add_column, etc.), migration statistics. |
config |
Cache store, session store, timezone, queue adapter, mailer settings, middleware stack, initializers, credentials status, CurrentAttributes classes. |
stimulus |
Stimulus controllers with targets, values (with types), actions, outlets, classes. Extracted from JS/TS files. |
view_templates |
View file contents, partial references, Stimulus data attributes, model field usage in partials. |
components |
ViewComponent/Phlex components: props, slots, previews, sidecar assets, usage examples. |
turbo |
Turbo Frames (IDs and files), Turbo Stream templates, model broadcasts (broadcasts_to, broadcasts). |
auth |
Devise models with modules, Rails 8 built-in auth, has_secure_password, policy classes in app/policies (named Pundit only when the app bundles it), an Ability class (named CanCanCan only when the app bundles it), CORS config, CSP config. |
performance |
N+1 query risks, missing counter_cache, missing FK indexes, Model.all anti-patterns, eager load candidates. |
i18n |
Default locale, available locales, locale files with key counts, backend class, parse errors. |
Full preset (40 introspectors) - default
Includes all standard introspectors plus:
| Introspector | What it discovers |
|---|---|
views |
Layouts, templates grouped by controller, partials (per-controller and shared), helpers with methods, template engines (erb, haml, slim), view components. |
active_storage |
Attachments (has_one_attached, has_many_attached per model), storage services, direct upload config. |
action_text |
Rich text fields (has_rich_text per model), Action Text installation status. |
api |
API-only mode, API versioning (from directory structure), serializers (Jbuilder, AMS, etc.), GraphQL (types, mutations), rate limiting (Rack::Attack). |
rake_tasks |
Custom rake tasks from the Rakefile, lib/tasks/ and rakelib/ (names, arguments, descriptions, namespaces, file paths); the app's generators under lib/generators, lib/templates overrides and the Railties under lib/. |
assets |
Asset pipeline (Propshaft/Sprockets), JS bundler (importmap/esbuild/webpack/vite), CSS framework, importmap pins, manifest files. |
devops |
Puma config (threads, workers, port), Procfile entries, Docker (multi-stage detection), deployment tools, health check routes. |
action_mailbox |
Action Mailbox mailboxes with routing patterns. |
seeds |
db/seeds.rb analysis (Faker usage, environment conditionals), seed files in db/seeds/, models seeded. |
middleware |
Custom Rack middleware in app/middleware/ and lib/middleware/ with detected patterns (auth, rate limiting, tenant isolation, logging), what the app's config inserts, moves or removes, and the full middleware stack. |
engines |
Mounted Rails engines from routes.rb with paths and descriptions for 23 known engines (Sidekiq::Web, Flipper::UI, PgHero, ActiveAdmin, etc.). |
env_config |
Per-environment config files (config/environments/*.rb): notable toggles (force_ssl, eager_load, caching, log level, queue adapter, mailer delivery) with URI credentials redacted, assigned config keys, plus the keys config/application.rb sets for every environment and the keys each config_for YAML file gives. |
multi_database |
Multiple databases, replicas, sharding config, model-specific connects_to declarations. database.yml parsing fallback. |
frontend_frameworks |
Frontend JS framework detection (React/Vue/Svelte/Angular), mounting strategy (Inertia/react-rails), TypeScript config, state management, package manager. |
database_stats |
PostgreSQL approximate row counts via pg_stat_user_tables. Gracefully skips on non-PostgreSQL adapters. |
initializers |
The Rails.application.initializers graph (name, owner, before:/after: edges) and a per-file summary of config/initializers/*.rb. |
autoload |
Zeitwerk autoloaders with collapsed and ignored dirs, autoload_paths, eager_load_paths, custom inflections. |
connection_pool |
Per-database adapter config: pool size, checkout_timeout, reaping_frequency, prepared_statements, replica flag, connection-handler roles. |
active_support |
Concerns in app/**/concerns/, deprecators, MessageEncryptor/Verifier usage, notification subscriptions, on-load hooks, cache store options. |
credentials |
Encrypted credentials files (default and per-environment), where the master key comes from, top-level key names only (never values). |
security |
force_ssl and SSL options, host authorization, Content Security Policy and Permissions Policy directives, CSRF config, cookie session options. |
observability |
Log subscribers, ActiveSupport::Notifications subscribers, ServerTiming middleware, log level and tags. |
env |
Rails-related ENV vars split into set and unset (sensitive ones are redacted), plus the app's own ENV["X"] references. |
Using the standard preset
config.preset = :standard
Cherry-picking introspectors
# Start with standard, add specific ones
config.preset = :standard
config.introspectors += %i[views turbo auth api]
# Or build from scratch
config.introspectors = %i[schema models routes gems auth api]
AI Assistant Setup
Claude Code
Auto-discovery: Reads .mcp.json when a session starts in the folder, and asks you to approve the rails-ai-context server once (claude mcp reset-project-choices asks again).
Context files loaded:
CLAUDE.md- read at conversation start. Where it holds@AGENTS.md, Claude Code expands the import and readsAGENTS.mdwith it.claude/rules/*.md- the schema, models and components rules load when Claude Code opens a file theirpaths:frontmatter matches; the overview and tools rules, written only withgenerate_root_filesoff, load in every session
MCP tools: Available once the server is approved. /mcp lists it.
Cursor
Auto-discovery: Reads .cursor/mcp.json. Restart Cursor after the install, and turn rails-ai-context on under MCP in Customize if it is off. The entry starts the server through a one-line ruby -e launcher, because the Cursor CLI passes a server no GEM_PATH, which rvm and chruby need (why).
Context files loaded:
AGENTS.mdandCLAUDE.md- read like an always-on rule, so the root content reaches Cursor fromAGENTS.md.cursor/rules/*.mdc- loaded based onalwaysApplyandglobssettings
MDC rule activation modes:
| Mode | When it activates |
|---|---|
alwaysApply: true |
Every conversation (project overview and tools guide, root files off) |
globs: ["app/models/**/*.rb"] |
When editing files matching the glob pattern |
OpenCode
Auto-discovery: opencode.json is auto-generated by the install generator. Or add manually:
{
"mcp": {
"rails-ai-context": {
"type": "local",
"command": ["bundle", "exec", "rails-ai-context", "serve"]
}
}
}
For standalone: use "command": ["rails-ai-context", "serve"] instead.
{
"mcp": {
"rails-ai-context": {
"type": "local",
"command": ["rails-ai-context", "serve"]
}
}
}
Context files loaded:
AGENTS.md- project overview + MCP tool guide, read at conversation startapp/models/AGENTS.md- model listing, auto-loaded when agent reads model filesapp/controllers/AGENTS.md- controller listing, auto-loaded when agent reads controller files- Falls back to
CLAUDE.mdif noAGENTS.mdexists
OpenCode uses per-directory lazy-loading: when the agent reads a file, it walks up the directory tree and auto-loads any AGENTS.md it finds. This is how split rules work - no globs or frontmatter needed.
MCP tools: Available via opencode.json (auto-generated or manual config above).
GitHub Copilot
Auto-discovery: .vscode/mcp.json (VS Code) and .github/mcp.json (Copilot CLI, which never reads the VS Code file) are auto-generated by the install generator. Copilot in JetBrains IDEs takes its entry from rails-ai-context mcp-entry (Other MCP clients). Copilot CLI loads .github/mcp.json only in a folder you trust; copilot mcp list shows the server.
Context files loaded:
.github/copilot-instructions.md- repo-wide instructions, the root content. github.com chat, Visual Studio, JetBrains, Xcode and code review read no other root file.github/instructions/*.instructions.md- path-specific, activated byapplyToglob (withname:anddescription:frontmatter)
applyTo patterns:
| Pattern | When it activates |
|---|---|
app/models/**/*.rb |
Editing model files |
app/controllers/**/*.rb |
Editing controller files |
**/* |
All files (project overview and tools guide, root files off) |
Codex CLI
Auto-discovery: .codex/config.toml is auto-generated by the install generator, with an env_vars list that passes your shell's Ruby variables to the server. In a new session the first step can run before the rails tools are up, since Codex waits about one second for a server still starting; required = true in the table makes it wait (AI tool setup).
Context files loaded:
AGENTS.md- project overview + MCP tool guide (shared with OpenCode)app/models/AGENTS.md- model listing, auto-loaded when agent reads model filesapp/controllers/AGENTS.md- controller listing, auto-loaded when agent reads controller files
MCP tools: Available via .codex/config.toml.
Stack Compatibility
| Setup | Coverage | Notes |
|---|---|---|
| Rails full-stack (ERB + Hotwire) | 40/40 | All introspectors relevant |
| Rails + Inertia.js (React/Vue) | Backend ones | Views/Turbo partially useful, backend fully covered |
| Rails API + React/Next.js SPA | Backend ones | Schema, models, routes, API, auth, jobs - all covered |
| Rails API + mobile app | Backend ones | Same as SPA - backend introspection is identical |
| Rails engine (mountable gem) | Core ones | Core introspectors (schema, models, routes, gems) work |
All 40 introspectors run on every setup with the default :full preset. The gem keeps no per-setup count: frontend introspectors (views, Turbo, Stimulus, assets) degrade gracefully - they report nothing when those features aren't present.
Tip for API-only apps:
# Use standard preset (it already has auth)
config.preset = :standard
# And add the API introspector, which standard leaves out
config.introspectors += %i[api]
Diagnostics
rails ai:doctor
Runs the checks below and reports an AI readiness score (0-100). A check that does not apply to the app prints no row:
| Check | What it verifies |
|---|---|
| Schema | A schema dump file exists |
| Pending migrations | No migration is pending in any database the app migrates, each read through its own connection as db:migrate:status reads it, and nothing written to it: a database never migrated gets no schema_migrations table from doctor (fails when one is pending) |
| Database | Shown in place of Pending migrations when a database the app migrates does not exist (fix: bin/rails db:prepare) or its server does not answer (fails). A SQLite database whose file is not there is named without connecting to it, since connecting would create an empty one |
| Models | Model files detected where the tools read them: app/models, packs and in-repo engines, and in an engine's test/dummy the engine's own |
| Routes | config/routes.rb exists |
| Gems | The app's lockfile exists, or the one its config/boot.rb names (a monorepo's shared bundle, an engine's for its test/dummy) |
| Controllers | Controller files detected, read as Models are |
| Views | Files exist where the tools read views: app/views, packs, and in an engine's test/dummy the engine's |
| Tests | A test suite is found: the app's, or in an engine's test/dummy the engine's |
| Migrations | Migration files exist, counted over every database the app migrates, and in an engine's test/dummy the engine's own |
| Context files | Generated context files exist where config.output_dir puts them, and a context run would leave them as they are. A file a run would rewrite, because an older version of the gem wrote it or the app changed under it, is named; a file that is only older than the code is not. In an engine's dummy app the install at the engine's root is read, and its own context command runs there, into a copy. No row on an MCP-only install |
| Initializer guard | Shown only when config/initializers/rails_ai_context.rb makes a RailsAiContext.configure call no guard covers (a guard in a comment, or an if that ends before the call, covers nothing), or guards on defined?(RailsAiContext) alone |
| MCP configs | Each selected tool's MCP config file exists, parses, and holds a rails-ai-context server whose command can start: bundle exec only where the app's lockfile carries the gem and the bundle's copy has its executable, the rails-ai-context binary only where it is on PATH, and a warning when a config runs that binary in an app whose bundle carries the gem. A Codex entry that still starts with the Ruby environment an earlier release saved warns, and fails when that saved PATH no longer reaches its command (fix: run the install). The command is looked up, never run. Skipped in CLI-only mode |
| MCP server | MCP server can be built, with an mcp gem this gem supports (warns, as the boot does, when the app's bundle pins one outside that range) |
| Introspector health | Every configured introspector returns data |
| Preset coverage | The preset covers the features the app has |
| ripgrep | rg binary installed (optional, falls back to Ruby) |
| Prism parser | Prism is available for AST-based validation, at a version this gem supports (warns, as the boot does, when the app's bundle pins one below it) |
| Brakeman | Brakeman is available for rails_security_scan (optional): in the app's bundle, or installed on the machine, where the scan runs the gem's own script as a process of its own. Doctor runs that script's --version the way the scan runs it, and warns, with what it printed, when it does not answer |
| Live reload | listen gem installed (optional, enables MCP live reload) |
| MCP stdio hygiene | On a standalone install, or where a config starts the rails-ai-context binary itself, gem activation prints nothing on stdout |
| Secrets in .gitignore | Secret files that exist are gitignored and not committed: config/master.key, config/credentials/*.key, every .env file, config/application.yml and SSH and cloud credentials (fails when one is not ignored, or is committed: the fix is git rm --cached and rotating it). config/database.yml, cable.yml, storage.yml and the like warn only when they hold a password, token or key as a literal value. The encrypted credentials.yml.enc is committed by design and never reported. Inside a git repository git answers, so a rule in a .gitignore above the app (a monorepo's), in .git/info/exclude or in the global excludes counts; outside one the app's .gitignore is read |
| MCP HTTP endpoint | allow_http_in_production is off, so the mounted engine and auto_mount refuse outside development and test; on, it warns, and with auto_mount it fails |
| Schema file size | The schema file is under 80% of max_schema_file_size |
| View aggregation size | app/views templates total under 80% of max_view_total_size |
Each check reports pass, warn, or fail with fix suggestions.
Watch Mode
Auto-regenerate context files when your code changes:
rails ai:watch
Requires the listen gem:
# Gemfile
gem "listen", group: :development
The standalone binary's rails-ai-context watch also finds a listen installed with gem install listen, the way it finds its own dependencies outside the app's bundle; a listen the app's bundle locks still wins.
Watches for changes in: app/, config/, db/, lib/, rakelib/, test/, spec/, plus the app directories of packs, in-repo engines and extra_app_paths, and regenerates only the files that changed (diff-aware, skips unchanged files).
Live Reload (MCP)
When running the MCP server via rails ai:serve, live reload notifies connected AI clients when files change, so they know to re-query.
Answers never wait on it. Every tool call and resource read first checks the watched files, with listen or without it (a new Rails 8 app does not bundle it), and when one changed it reloads the app's code and drops the caches - so an answer sees every edit made before the call began, one made a moment earlier included, which listen would deliver only after its debounce. The check stats each watched directory and file and reads a directory again only when it changed: about a millisecond on a small app, about 30 ms at 10,000 files. Calls made at the same time, over HTTP, wait for one check together; calls one after another each check.
A server whose app cannot reload code - RAILS_ENV=test, or production with eager loading, where config.enable_reloading is off - keeps the code it booted with. What reflection reads, such as associations and enums, then stays as of boot (validations and callbacks are read off the source, so they still follow the edit), and once a file under the app's autoload paths changes, every answer ends with a note naming it: restart the server to see the edit.
One save a reload can miss: Bootsnap's compile cache knows a Ruby file by its size and the second of its mtime, so a file saved twice within one second at the same size can reload as the first save. Every answer then names the file until it is saved again a second later (Known limits).
How it works
- A background thread watches
app/,config/,db/,lib/,rakelib/,test/andspec/(plus the app directories of packs, in-repo engines andextra_app_paths) for changes - On change (debounced 1.5s), it checks the file fingerprint to avoid false positives
- If files truly changed, it:
- Sends
notifications/resources/list_changedto the AI client - Logs a summary of what changed (e.g., "Files changed: 2 models, 1 controller.")
- Sends
The code reload and the cache drop are the calls' own: the first call after an edit makes them, on its own thread, when it checks the files. The watching thread loads none of the app's code.
Setup
Add the listen gem (you may already have it from Watch Mode):
# Gemfile
gem "listen", group: :development
The standalone binary's rails-ai-context serve also finds a listen installed with gem install listen, as watch does; a listen the app's bundle locks still wins.
Live reload is enabled by default when the listen gem is available. No configuration needed.
Configuration
if defined?(RailsAiContext) && RailsAiContext.respond_to?(:configure)
RailsAiContext.configure do |config|
# :auto (default) - enable if `listen` gem is available, otherwise skip with one line on stderr
# true - enable, raise if `listen` gem is missing
# false - disable entirely
config.live_reload = :auto
# Debounce interval in seconds (default: 1.5)
config.live_reload_debounce = 1.5
end
end
Difference from Watch Mode
Watch Mode (rails ai:watch) |
Live Reload (rails ai:serve) |
|
|---|---|---|
| Trigger | File changes | File changes |
| Action | Regenerates static context files (CLAUDE.md, etc.) | Invalidates MCP tool caches + notifies AI client |
| Use case | Keep committed files up to date | Keep live MCP sessions fresh |
| Transport | N/A (writes to disk) | stdio and HTTP |
Works Without a Database
The gem gracefully degrades when no database is connected. The schema introspector parses db/schema.rb as text instead of querying information_schema.
Works in:
- CI/CD pipelines
- Claude Code sessions (no DB running)
- Docker build stages
- Read-only environments
- Any environment with source code but no running database
Security
- All MCP tools are read-only - they never modify your application or database
- Code search uses
Open3.capture3with array arguments - no shell injection - File paths are validated against path traversal attacks
- Credentials and secret values are never exposed - only key names are introspected
- The gem makes no outbound network requests
- File type validation prevents arbitrary file access in code search
- Search output is capped at
max_search_resultslines (default 200) to prevent resource exhaustion
Troubleshooting
MCP server not detected by your AI tool
- Run
rails ai:doctor- it checks per-tool MCP config files - Verify the correct config file exists for your tool (
.mcp.json,.cursor/mcp.json,.vscode/mcp.json,.github/mcp.json,opencode.json,.codex/config.toml) in the folder the tool opened: the app, or the folder of appsinitset up - Re-run install (
rails generate rails_ai_context:installorrails-ai-context init) to regenerate configs - Restart your AI tool
Context files are too large
# Switch to compact mode (default in v0.7+)
config.context_mode = :compact
MCP tool responses are too large
# Lower the safety cap
config.max_tool_response_chars = 60_000
Schema not detected
- Ensure
db/schema.rbexists (runrails db:schema:dumpif needed) - The gem works without a database - it parses schema.rb as text
Models not detected
- Models must descend from
ActiveRecord::Base, throughApplicationRecordor any other base class. Without a boot they must also sit in a model directory (app/models/, or a pack's or engine's) - A file in a
concerns/directory of a model root is a model when the class its path names has a model superclass. A concern module that holds an inner class stays a concern. Without a boot, such a class is not listed when its superclass is a gem's own record base. The booted tier resolves it through the loaded class - Excluded models:
ApplicationRecord,ActiveStorage::*,ActionText::*,ActionMailbox::* - Add custom exclusions:
config.excluded_models += %w[InternalModel]
Ripgrep not found
Code search falls back to Ruby's Dir.glob + File.read. Install ripgrep for faster search:
# macOS
brew install ripgrep
# Ubuntu/Debian
sudo apt install ripgrep
Watch mode not working
# Install listen gem
bundle add listen --group development
# Then run
rails ai:watch
# Standalone install: no Gemfile change
gem install listen
rails-ai-context watch
Tool responses show "not available"
The tool's introspector isn't in the active preset. Either:
# Use full preset
config.preset = :full
# Or add the specific introspector
config.introspectors += %i[config] # for rails_get_config
config.introspectors += %i[tests] # for rails_get_test_info