Logo: rails-ai-context

rails-ai-context

Communautéit
crisnahine

45 MCP tools that give AI coding agents ground truth about your Rails app: schema, models, routes, controllers, views, jobs, conventions. Works with Claude Code, Cursor, GitHub Copilot, OpenCode and Codex CLI. MCP or CLI, in-Gemfile or standalone, and it still answers when the app can't boot.

Editeurcrisnahine
Repositoryrails-ai-context
SproochRuby
Forks
13
Stären
158
Disponibel Tools
0
Transporttypstdio
Kategorien
LizenzMIT
Linken
  • Tools mat KI-Workflows verbannen

    rails-ai-context bitt MCP-Funktiounen un, déi vu kompatibele KI-Clienten a KI-Agente kënne benotzt ginn.

  • Disponibel Tools: 0

    Kuckt Iech déi opruffbar Aktiounen hei drënner un, mat Nimm a Beschreiwungen, wa se vum Server geliwwert ginn.

  • Konfiguratioun fir ze kopéieren

    Benotzt d'Installatiounsbeispiller, fir dëse Server an deem MCP-Client ze konfiguréieren, deen Dir am léifste benotzt.

  • Interessi vun der Communautéit um Open-Source-Projet

    Zuele vum verlinkte Repository – Stären: 158, Forks: 13.

rails-ai-context

Give your AI coding assistant ground truth about your Rails app

Gem Version Downloads CI MCP Registry Ruby Rails License

Claude Code Cursor GitHub Copilot OpenCode Codex CLI Any terminal

:star: If this gem saves you a correction loop, star it on GitHub!

Why • Features • Getting started • Usage • Tools • Configuration • Documentation

Install demo

rails-ai-context is a Ruby gem that turns your Rails app into the source of truth for AI coding assistants. Instead of guessing your schema, associations, routes and conventions from training data, the assistant asks your app: 45 read-only tools served over MCP or run from the CLI, plus generated context files for Claude Code, Cursor, GitHub Copilot, OpenCode and Codex CLI.

[!TIP] Nothing to add to your Gemfile if you don't want to. gem install rails-ai-context, then rails-ai-context init inside any Rails app. It also works on an app that won't boot: pass --no-boot and every tool answers from the source files.

Why

You have seen your assistant do these:

  • Write a migration for a column that already exists.
  • Call user.posts when the association is user.articles.
  • Scaffold tests with FactoryBot in a fixture-based suite.
  • Miss a before_action inherited from a parent controller, then wonder why auth fails.
  • Add a gem you already have, or call an API from one you don't.
  • Invent a method that isn't in the codebase.

You catch it, fix it, re-prompt, and something next to it breaks. The tokens are cheap; the correction loop is what costs you the afternoon. This gem removes the guess at the source.

You ask the AI to...WithoutWith
Add a subscription_tier column to usersWrites the migration, duplicates an existing columnReads the live schema, sees subscription_status, asks before migrating
Call user.posts in a controllerGuesses; NoMethodError at runtimeResolves the real association from the model
Write tests for a new modelScaffolds with FactoryBotDetects your fixture-based suite and matches it
Fix a failing create actionMisses the inherited authenticate_user!Gets parent-controller filters inline with the action source
Build a dashboard pageInvents Tailwind classes from memoryGets your real button/card/alert patterns
Trace where publishable? is usedReads 6 files in sequence, still misses callersOne call: definition + source + every caller + tests

Trace demo

Features

  • 45 read-only tools for schema, models, controllers, routes, views, Stimulus, Turbo, jobs, services, mailers, i18n, gems, config, tests, security, performance and more. Every answer comes from your app.
  • Prism AST parsing for model introspection. Each result carries [VERIFIED] or [INFERRED] so the assistant knows what is ground truth and what needs a runtime check.
  • Three ways in: MCP over stdio, MCP mounted inside your Rails app over HTTP, or plain CLI in any terminal.
  • Generated context files for Claude Code, Cursor, GitHub Copilot, OpenCode and Codex CLI, with the MCP config each tool auto-detects on project open.
  • Live resources: rails:// and rails-ai-context:// URIs that introspect fresh on every read.
  • Anti-hallucination rules shipped in every generated context file, on by default.
  • Static tier: when the app can't boot, tools answer from config/routes.rb, db/schema.rb, migrations and source files, and say so.
  • Works with real app shapes: packwerk packs, in-repo engines, multi-database schema dumps, Mongoid, API-only apps.
  • Custom tools: register your own MCP::Tool classes next to the built-in ones and test them with the bundled TestHelper.

Getting started

Requirements

  • Ruby 3.1 or newer
  • Rails 7.0 or newer
  • Optional: brakeman for security_scan, listen for watch, ripgrep for faster search_code

Install in the Gemfile

bash
bundle add rails-ai-context --group development
rails generate rails_ai_context:install

The generator asks which AI tools you use and what to write, then creates the context files, the MCP config for each tool, and config/initializers/rails_ai_context.rb. Re-running it is safe; it keeps what you have and adds what is missing.

Keeping your own CLAUDE.md and AGENTS.md? rails generate rails_ai_context:install --mcp-only writes the MCP config and leaves every context file alone.

Install standalone

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

No Gemfile change. Config lives in .rails-ai-context.yml. Works with rbenv, rvm, asdf, mise, chruby and system Ruby. See Standalone.

Check it works

bash
rails ai:doctor                                  # in-Gemfile: readiness score + diagnostics
rails-ai-context doctor                          # standalone

rails 'ai:tool[schema]' table=users
rails 'ai:tool[model_details]' model=User
rails 'ai:tool[search_code]' pattern=publishable? match_type=trace

Then open the project in your AI tool. The MCP config it wrote is picked up on open, and the assistant starts calling rails_get_model_details instead of guessing.

[!NOTE] The CLI commands above are for you. When MCP is connected the assistant calls the same tools itself; you never type them.

Usage

MCP over stdio

The default. Each AI tool gets its own config file (.mcp.json, .cursor/mcp.json, .vscode/mcp.json, opencode.json, .codex/config.toml) pointing at:

bash
rails ai:serve             # in-Gemfile
rails-ai-context serve     # standalone

MCP over HTTP

Mount the server inside your app. It inherits your routing, auth and middleware, and needs no second process.

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

Point the client at http://localhost:3000/mcp. There is also a standalone HTTP process: rails-ai-context serve --transport http --port 6029.

[!WARNING] Each connected client that opens the SSE channel holds one server thread for the life of the connection. Fine for development; raise Puma's thread count or use the standalone HTTP process if several clients share the app.

CLI

Same 45 tools, no server, any terminal.

bash
rails 'ai:tool[search_code]' pattern="publishable?" match_type=trace
rails-ai-context tool schema --table users --detail full

Tool names resolve loosely: schema, get_schema and rails_get_schema all work. Most tools take detail=summary|standard|full.

Commands

In-GemfileStandaloneWhat it does
rails ai:serverails-ai-context serveStart the MCP server (stdio)
rails ai:serve_httprails-ai-context serve --transport httpStart the MCP server (HTTP)
rails 'ai:tool[NAME]'rails-ai-context tool NAMERun one tool
rails ai:toolrails-ai-context tool --listList the tools
rails ai:contextrails-ai-context contextGenerate context files
rails ai:doctorrails-ai-context doctorDiagnostics and readiness score
rails ai:watchrails-ai-context watchRegenerate on file change
rails 'ai:preset[NAME]'rails-ai-context preset NAMERun a multi-tool preset (architecture, debugging, migration)

Flags shared by the app-reading commands: --app-path PATH to target another directory, --environment ENV to set RAILS_ENV, and --no-boot to skip the boot attempt and answer from source. Full list in the CLI reference.

Tools

Every tool is read-only and answers from your app.

CategoryTools
Search and tracesearch_code, get_edit_context
Understandanalyze_feature, get_context, onboard
Schema and modelsget_schema, get_model_details, get_callbacks, get_concern
Controllers and routesget_controllers, get_routes
Views and frontendget_view, get_stimulus, get_partial_interface, get_turbo_map, get_frontend_stack
Testing and qualityget_test_info, generate_test, validate, security_scan, performance_check
App config and servicesget_api, get_conventions, get_config, get_gems, get_env, get_helper_methods, get_service_pattern, get_job_pattern, get_component_catalog, get_i18n, get_mailers, get_engines, get_autoload, get_active_support, get_env_config
Data and debuggingdependency_graph, migration_advisor, search_docs, query, read_logs, diagnose, review_changes, runtime_info, session_context

A few worth knowing on day one:

  • search_code with match_type=trace returns definition, source, every caller grouped by type, and the tests, in one call. That replaces 4 to 5 file reads.
  • get_controllers returns the action source with inherited filters, strong params and the render map.
  • get_model_details returns associations, validations, scopes, enums and macros from the AST, each tagged [VERIFIED] or [INFERRED].
  • query runs read-only SQL with a timeout, a row limit and column redaction. read_logs redacts sensitive data before it leaves the process.

Parameters for all 45 are in the tools reference; worked examples in recipes.

Live resources

MCP clients can also read structured data as resources. Templates introspect fresh on every request:

URIReturns
rails-ai-context://models/{name}Associations, validations, schema for one model
rails-ai-context://controllers/{name}Actions, inherited filters, strong params
rails-ai-context://controllers/{name}/{action}Action source with the filters that apply
rails-ai-context://views/{path}View template content (path traversal blocked)
rails-ai-context://routes/{controller}Live route map for one controller

The legacy rails://models/{name} form is still accepted.

Plus 9 static resources: rails://schema, routes, conventions, gems, controllers, config, tests, migrations, engines.

Anti-hallucination rules

Every generated context file (CLAUDE.md, .cursor/rules/, .github/instructions/, AGENTS.md) ships with six rules the assistant reads before writing code:

  1. Verify before you write. Never reference a column, association, route, helper, method, class, partial or gem that a tool call in this turn did not confirm.
  2. Mark every assumption with [ASSUMPTION]. "I'd need to check X first" is a good answer.
  3. Training data describes average Rails. This app isn't average. When something feels obviously standard, query anyway.
  4. Check the inheritance chain before every edit: inherited filters, concerns, includes, STI parents.
  5. Empty tool output is information. "0 callers found" means investigate, it does not mean proceed.
  6. Stale context lies. Re-query after writes.

On by default. Turn off with config.anti_hallucination_rules = false if you prefer your own.

When the app can't boot

rails-ai-context tries a full boot for live reflection. When boot fails (missing ENV vars, an unreachable service, a broken initializer) the app-reading commands fall back to the static tier instead of dying: routes from config/routes.rb, schema from db/schema.rb, db/structure.sql or migrations, models and controllers from their source files. Every response carries a banner naming the degradation, static data is tagged [STATIC], and sections that need a booted app report [UNAVAILABLE] with the reason.

--no-boot skips the attempt outright, which is fast and immune to boot-time side effects. doctor still needs a bootable app; diagnosing the boot is its job.

Code is found in the conventional layout, in packwerk packs (packs/*/app/*), in in-repo engines (engines/*/app/*), and in any extra_app_paths from .rails-ai-context.yml. Multi-database schema dumps (db/queue_schema.rb and friends) show up under a Secondary databases section. Mongoid apps get an [UNAVAILABLE] schema signal plus static model data instead of an empty table, and API-only apps get "not applicable" from the view and frontend tools instead of a silent blank. Details in Compatibility.

Configuration

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

Standalone installs use the same keys in .rails-ai-context.yml. All options with defaults are in Configuration.

Custom tools

Register your own tools next to the built-in ones:

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

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

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

Test them with the bundled helper (RSpec or Minitest):

ruby
include RailsAiContext::TestHelper

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

See Custom tools.

Observability

Every MCP call fires an ActiveSupport::Notifications event:

ruby
ActiveSupport::Notifications.subscribe("rails_ai_context.tools.call") do |event|
  ms = (event.payload[:duration].to_f * 1000).round
  Rails.logger.info "[MCP] #{event.payload[:tool_name]} #{ms}ms"
end

How it works

Internals, the introspector list and the AST engine are in Architecture and Introspectors.

Documentation

QuickstartUp and running in 5 minutes
GuideEvery command, parameter and option
Tools referenceAll 45 tools with every parameter
RecipesReal workflows, end to end
AI tool setupClaude Code, Cursor, Copilot, OpenCode, Codex CLI, HTTP transport
CLI referenceCommands, flags and argument syntax
StandaloneUse without a Gemfile entry
ConfigurationEvery option with its default
Custom toolsBuild and test your own tools
ArchitectureSystem design and internals
IntrospectorsAll 40 introspectors and the AST engine
SecuritySQL safety layers and file blocking
CompatibilitySupported versions, operating tiers, app shape matrix
TroubleshootingCommon problems and fixes
FAQFrequently asked questions

Built by a Rails developer with 10+ years in production. If it saves you time, consider sponsoring the project.

Installatioun

TypingMind
Viraussetzungen:

Node.js 18+

{
  "mcpServers": {
    "crisnahine-rails-ai-context": {
      "command": "",
      "args": []
    }
  }
}

rails-ai-context MCP mat verschiddene KI-Modeller benotzen

TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Soubal rails-ai-context verbonnen ass, kënnt Dir et mat verschiddene KI-Modeller an TypingMind benotzen, amplaz et fir all Modell separat anzeriichten. Dës MCP-Integratioun leeft lokal iwwer den TypingMind-MCP-Connector op Ärem Apparat.

Ariichtungsuleedung, fir de lokale Connector ze benotzen

Benotzt dës Optioun, wann den MCP-Server Zougrëff op lokal Fichieren, Appen oder privat Ressourcen op Ärem Computer brauch.

1

D'MCP-Astellungen opmaachen

Gitt an TypingMind op „Astellungen“, „Erweidert Astellungen“, dann op „Model Context Protocol“ a wielt „Connector ariichten“.

  1. Maacht TypingMind an Ärem Browser op.
  2. Klickt op d'Astellungssymbol.
  3. Gitt op „Erweidert Astellungen“.
  4. Maacht d'Sektioun „Model Context Protocol“ op.
  5. Klickt op „Connector ariichten“ a wielt „Dësen Apparat“.
Ariichtungsbildschierm vum TypingMind-MCP-Connector: D'Optioun „Dësen Apparat“ ass ausgewielt
2

De Connector-Befeel ausféieren

Wielt „Dësen Apparat“, kopéiert de Befeel aus TypingMind a féiert en am Terminal aus. Loosst de Prozess lafen, wärend Dir MCP benotzt.

  1. Kopéiert den Ariichtungsbefeel, deen TypingMind uweist.
  2. Maacht Terminal op macOS oder Windows Terminal op Windows op.
  3. Setzt de kopéierte Befeel an a féiert en aus.
  4. Bestätegt d'Installatioun vum Package, wann den Terminal Iech freet, ob Dir weiderfuere wëllt.
  5. Loosst den Terminal an de Prozess doranner lafen, wärend Dir MCP-Tools benotzt.
3

rails-ai-context als Server derbäisetzen

Wann de Connector-Status „Prett“ ass, klickt op „Serveren änneren“ a setzt d'MCP-Serverkonfiguratioun an.

  1. Waart, bis de Connector-Status „Prett“ weist.
  2. Klickt op „Serveren änneren“.
  3. Setzt d'MCP-Serverkonfiguratioun fir rails-ai-context an.
  4. Späichert d'Serverlëscht.
  5. Aktualiséiert d'Säit, wann Dir kontrolléiere wëllt, ob de Connector nach ëmmer prett ass.
MCP-Astellunge vun TypingMind mat aktivem Server an dem Knäppchen „Serveren änneren“
{
  "mcpServers": {
    "crisnahine-rails-ai-context": {
      "command": "npx",
      "args": [
        "-y",
        "rails-ai-context"
      ]
    }
  }
}
4

D'Verbindung mat verschiddene Modeller benotzen

Späichert d'Serverlëscht, maacht „Plugins“ op an aktivéiert d'MCP-Tools vun der Integratioun rails-ai-context. Wielt dann e belibegen ënnerstëtzte KI-Modell an TypingMind a benotzt d'Tools am Chat oder weist se engem KI-Agent zou.

  1. Maacht d'Säit „Plugins“ an TypingMind op.
  2. Aktivéiert d'MCP-Tools vun der Integratioun rails-ai-context.
  3. Start e Chat a wielt de KI-Modell, deen Dir benotze wëllt.
  4. Benotzt d'MCP-Tools am Chat oder weist se engem KI-Agent zou.
  5. Wiesselt bei Bedarf op en anere KI-Modell, ouni MCP nei ze verbannen.
TypingMind-Chat mat aktivéierten MCP-Tools an engem ausgewielte KI-Modell
Kënnt Dir mir mat rails-ai-context bei dëser Aufgab hëllefen?
rails-ai-context
Jo. Ech hunn et gelies.
Dat hunn ech mat rails-ai-context fonnt.

Heefeg gestallte Froen

Fir wat gëtt den MCP-Server rails-ai-context benotzt?

rails-ai-context ass en MCP-Server, deen et kompatibele KI-Clienten erlaabt, op extern Tools a Kontextinformatioune zouzegräifen. An TypingMind kënnt Dir dësen MCP-Server eemol derbäisetzen a seng Tools an Ärem KI-Aarbechtsberäich zur Verfügung stellen.

Kann ech rails-ai-context MCP mat méi KI-Modeller an TypingMind benotzen?

Jo. TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Sou kënnt Dir rails-ai-context mat verschiddene KI-Modeller wéi Claude, ChatGPT, Gemini oder anere Modeller benotzen, déi Dir an TypingMind konfiguréiert hutt, ouni den MCP-Server fir all Modell separat anzeriichten.

Firwat rails-ai-context MCP mat TypingMind benotzen?

TypingMind ass eng vun de beschte Benotzeruewerfläche fir LLM-Chat, well et méi KI-Modeller, Prompts, Plugins, KI-Agenten, API-Schlësselen a MCP-Tools an engem Aarbechtsberäich zesummebréngt. Wann rails-ai-context verbonnen ass, kënnt Dir seng MCP-Tools mat Äre bevorzugte Modeller benotzen a gläichzäiteg Ären Aarbechtsoflaf beim Chatten an TypingMind organiséieren.

Wéi verbannen ech rails-ai-context MCP mat TypingMind?

rails-ai-context leeft iwwer de lokale MCP-Connector vun TypingMind. Dat eegent sech am beschten, wann den MCP-Server Zougrëff op lokal Fichieren, Desktop-Apps, Kommandozeilen-Tools oder privat Ressourcen op Ärem Computer brauch.

Wéi eng Tools stellt rails-ai-context MCP an TypingMind zur Verfügung?

rails-ai-context stellt MCP-Funktioune zur Verfügung, déi Dir op der Plugins-Säit vun TypingMind aktivéiere kënnt, fir se am Chat ze benotzen oder KI-Agente zouzeweisen.

Muss ech meng API-Schlëssele mat TypingMind deelen, fir rails-ai-context MCP ze benotzen?

Nee. TypingMind ass nom Local-first-Prinzip opgebaut a léisst Iech d'Kontroll iwwer Är Modellubidder, API-Schlësselen, Prompts a MCP-Konfiguratioun. Wann rails-ai-context eng Authentifizéierung verlaangt, setzt déi néideg Headeren, OAuth-Astellungen oder lokal Konfiguratioun fir deen MCP-Server derbäi, wann Dir d'Verbindung erstallt.

Änlech MCP-Serveren

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇