freshcrate
Skin:/
Home > MCP Servers > rails-ai-context

rails-ai-context

Auto-introspect your Rails app and expose it to AI assistants. 38 tools, zero config, works with Claude, Cursor, Copilot, and any MCP client.

Why this rank:Strong adoptionRecent releaseHealthy release cadence

Description

Auto-introspect your Rails app and expose it to AI assistants. 38 tools, zero config, works with Claude, Cursor, Copilot, and any MCP client.

README

rails-ai-context

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

Claude CodeCursorGitHub CopilotOpenCodeCodex CLIAny TerminalGem Version Downloads CI MCP Registry
Ruby Rails Tests License: MIT

The problem

You've seen it. Your AI:

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

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

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


Two commands. Problem gone.

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

Or standalone โ€” no Gemfile needed

gem install rails-ai-context
cd your-rails-app
rails-ai-context init     # interactive setup
rails-ai-context serve    # start MCP server

Install demo

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


See the difference

Trace demo

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


What stops being wrong

Real scenarios where AI goes sideways โ€” and what it does instead with ground truth:

You ask AI to... Without โ€” AI guesses With โ€” AI verifies first
Add a subscription_tier column to users Writes the migration, duplicates an existing column Reads live schema, spots subscription_status already exists, asks before migrating
Call user.posts in a controller Uses the guess; runtime NoMethodError Resolves the actual association (user.articles) from the model
Write tests for a new model Scaffolds with FactoryBot Detects your fixture-based suite and matches it
Fix a failing create action Misses inherited before_action :authenticate_user! Returns parent-controller filters inline with the action source
Build a dashboard page Invents Tailwind classes from memory Returns your actual button/card/alert patterns, copy-paste ready
Trace where publishable? is used Reads 6 files sequentially, still misses callers Single call: definition + source + every caller + tests
Verify it on your own app

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

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

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

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

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

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


Three ways to use it

MCP Server (stdio)

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

rails ai:serve
โ†’ rails_search_code(pattern: "publishable?", match_type: "trace")
โ†’ rails_get_schema(table: "users")
โ†’ rails_analyze_feature(feature: "billing")

MCP Server (HTTP)

Mount inside your Rails app โ€” inherits routing, auth, and middleware.

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

Native Rails controller transport. No separate process needed.

CLI

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

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

Full Guide โ†’ โ€” every command, every parameter, every configuration option.


Real-world examples

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

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

"Fix the broken post creation flow"
rails 'ai:tool[controllers]' controller=PostsController action=create
# PostsController#create

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

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

"Build a new dashboard view"
# Check existing view patterns
rails 'ai:tool[view]' controller=dashboard
# โ†’ templates with ivars, Turbo frames, Stimulus controllers, partial locals

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

# Get Stimulus data-attributes
rails 'ai:tool[stimulus]' controller=chart
# โ†’ correct HTML with dashes (not underscores) + reverse view lookup

38 Tools

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

Search & Trace
Tool What it does
search_code Trace: definition + source + callers + tests. Also: definition, call, class filters
get_edit_context Method-aware code extraction with class context
Understand
Tool What it does
analyze_feature Full-stack: models + controllers + routes + services + jobs + views + tests
get_context Composite: schema + model + controller + routes + views in one call
onboard Narrative app walkthrough (quick/standard/full)
Schema & Models
Tool What it does
get_schema Columns with indexed/unique/encrypted/default hints
get_model_details AST-parsed associations, validations, scopes, enums, macros โ€” each result tagged [VERIFIED] or [INFERRED]
get_callbacks Callbacks in Rails execution order with source
get_concern Concern methods + source + which models include it
Controllers & Routes
Tool What it does
get_controllers Actions + inherited filters + render map + strong params
get_routes Code-ready helpers (post_path(@record)) + required params
Views & Frontend
Tool What it does
get_view Templates with ivars, Turbo wiring, Stimulus refs, partial locals
get_stimulus HTML data-attributes (dashes!) + targets + values + actions
get_partial_interface What locals to pass + what methods are called on them
get_turbo_map Broadcast โ†’ subscription wiring + mismatch warnings
get_frontend_stack React/Vue/Svelte/Angular, Hotwire, TypeScript, package manager
Testing & Quality
Tool What it does
get_test_info Fixtures + relationships + test template matching your patterns
generate_test Test scaffolding matching your project's patterns
validate Syntax + semantic + Brakeman security in one call
security_scan Brakeman static analysis โ€” SQL injection, XSS, mass assignment
performance_check N+1 risks, missing indexes, counter_cache, eager load candidates
App Config & Services
Tool What it does
get_conventions Auth checks, flash messages, create action template, test patterns
get_config Database, auth framework, assets, cache, queue, Action Cable
get_gems Notable gems with versions, categories, config file locations
get_env Environment variables + credentials keys (not values)
get_helper_methods App + framework helpers with view cross-references
get_service_pattern Interface, dependencies, side effects, callers
get_job_pattern Queue, retries, guard clauses, broadcasts, schedules
get_component_catalog ViewComponent/Phlex: props, slots, previews, sidecar assets
Data & Debugging
Tool What it does
dependency_graph Model/service dependency graph in Mermaid or text format
migration_advisor Migration code generation with reversibility + affected models
search_docs Bundled topic index with weighted keyword search
query Safe read-only SQL with timeout, row limit, column redaction
read_logs Reverse file tail with level filtering and sensitive data redaction
diagnose One-call error diagnosis with classification + context + git + logs
review_changes PR/commit review with per-file context + warnings
runtime_info Live DB pool, table sizes, pending migrations, cache stats, queue depth
session_context Session-aware context tracking across tool calls

All 38 tools with parameters โ†’ ย |ย  Real-world recipes โ†’


Live Resources (VFS)

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

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

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


Anti-Hallucination Protocol

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

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

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


How it works

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

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

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

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

Install

Option A โ€” In Gemfile:

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

Option B โ€” Standalone (no Gemfile entry needed):

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

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


Commands

In-Gemfile Standalone What it does
rails ai:context rails-ai-context context Generate context files
rails 'ai:tool[NAME]' rails-ai-context tool NAME Run any of the 38 tools
rails ai:tool rails-ai-context tool --list List all available tools
rails ai:serve rails-ai-context serve Start MCP server (stdio)
rails ai:doctor rails-ai-context doctor Diagnostics + AI readiness score
rails ai:watch rails-ai-context watch Auto-regenerate on file changes

Documentation

Quickstart 5-minute getting started
Tools Reference All 38 tools with every parameter
Recipes Real-world workflows and examples
Custom Tools Build and test your own MCP tools
Configuration 40+ config options with defaults
AI Tool Setup Claude, Cursor, Copilot, OpenCode, Codex
Architecture System design and internals
Introspectors All 39 introspectors and AST engine
Security 4-layer SQL safety and file blocking
CLI Reference Commands and argument syntax
Standalone Use without Gemfile entry
Troubleshooting Common issues and fixes
FAQ Frequently asked questions

Build your own tools

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

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

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

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

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

include RailsAiContext::TestHelper

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

Custom Tools Guide โ†’


Configuration

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

All 40+ configuration options โ†’


Observability

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

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

Requirements

  • Ruby >= 3.2 ย ย  Rails >= 7.1
  • Optional: brakeman for security scanning, listen for watch mode, ripgrep for fast search


About

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


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


MIT License

Release History

VersionChangesUrgencyDate
v5.11.1 ### Fixed - E2E MCP HTTP protocol spec sends `initialize` once per session instead of per-test, fixing compatibility with newer `mcp` gem versions that reject duplicate initialization.High5/24/2026
v5.10.0 ### Added โ€” 8 new introspectors closing RAILS_NERVOUS_SYSTEM.md gaps An audit against [`RAILS_NERVOUS_SYSTEM.md`](RAILS_NERVOUS_SYSTEM.md) identified 9 framework sections where introspection was missing or partial. This release ships the 8 introspectors needed to close them (the 9th โ€” ยง11 Query interface โ€” was already covered by `:conventions` via `load_async` / `.async_*` scanning). All are wired into `PRESETS[:full]`. The gem now exposes **39 introspectors** (up from 31). - **`InitializerInHigh4/20/2026
v5.9.1 ### Fixed โ€” `GetConcern` missed plural concern names (#78) Thanks to [@johan--](https://github.com/johan--) for the report and fix. `rails_get_concern`'s includer search built its include-pattern regex via `String#classify`, which singularizes its input. Concerns with intentionally plural module names โ€” `WorksheetImports`, `PaperTrailEvents`, `SoftDeletables`, etc. โ€” got demodulized to `WorksheetImport` and the `include WorksheetImports` line in the model never matched. The tool reported no iHigh4/20/2026
v5.9.0 ### Fixed โ€” Cursor chat agent didn't detect rules Real user report during release QA: the Cursor IDE's chat agent didn't pick up rules written only as `.cursor/rules/*.mdc`, even when the rule declared `alwaysApply: true`. Cursor has **two** rule systems and the chat-agent composition path still consults the legacy `.cursorrules` file in many current builds. `CursorRulesSerializer` now writes **both**: `.cursor/rules/*.mdc` (newer format with frontmatter / glob scoping / agent-requested triggHigh4/16/2026
v5.8.1 ### Fixed โ€” Security Hardening Four exploitable vulnerabilities across `rails_query`, the VFS URI dispatcher, and the instrumentation bridge, plus six defense-in-depth hardening issues. All discovered by security and deep code-review passes conducted during v5.8.1 pre-release verification. None were known at the v5.8.0 release โ€” **users should upgrade immediately**. - **SQL column-aliasing redaction bypass (exploitable).** Post-execution redaction in `rails_query` operated on `result.columns`High4/15/2026
v5.8.0 ### Added โ€” Modern Rails Coverage Pass Five targeted gaps in modern Rails introspection, identified by an audit of the introspectors against current Rails 7/8 patterns. Net result: the gem now surfaces what AI agents need to know about Rails 8 built-in auth, Solid Errors, async query usage, strong_migrations safety, and Action Cable channel detail. - **Rails 8 built-in auth depth.** `auth_introspector#detect_authentication` previously detected `bin/rails generate authentication` only as a booHigh4/14/2026
v5.7.1 ### Changed โ€” SLOP Cleanup Internal code quality improvements โ€” no API changes, no new features. - **Extract `safe_read`, `max_file_size`, `sensitive_file?` to BaseTool** โ€” removed 16 duplicate one-liner methods across 8 tool files (get_env, get_job_pattern, get_service_pattern, get_turbo_map, get_partial_interface, get_view, get_edit_context, get_model_details, search_code) - **Extract `FullSerializerBehavior` module** โ€” deduplicated identical `footer` and `architecture_summary` methods fromHigh4/9/2026
v5.7.0 ### Quickstart โ€” Two commands. Problem gone. ```bash gem "rails-ai-context", group: :development rails generate rails_ai_context:install ``` ### Fixed โ€” Bug Fixes from Codebase Audit 6 bug fixes discovered via automated codebase audit (bug-finder, code-reviewer, doc-consistency-checker agents). - **AnalyzeFeature service/mailer method extraction** (HIGH) โ€” `\A` (start-of-string) anchor in `scan` regex replaced with `^` (start-of-line). Services and mailers now correctly list all methods insMedium4/9/2026
v5.6.0 ### Added โ€” Auto-Registration, TestHelper & Bug Fixes Developer experience improvements inspired by action_mcp patterns, plus 5 security/correctness bug fixes. - **Auto-registration via `inherited` hook** โ€” Tools are now auto-discovered from `BaseTool` subclasses. No manual list to maintain โ€” drop a file in `tools/` and it's registered. `Server.builtin_tools` is the new public API. Thread-safe via `@registry_mutex` with deadlock-free design (const_get runs outside mutex to avoid recursive locHigh4/9/2026
v5.4.0 ### Added โ€” Phase 3: Dynamic VFS & Live Resource Architecture (Ground Truth Engine Blueprint #39) Live Virtual File System replaces static resource handling. Every MCP resource is introspected fresh on every request โ€” zero stale data. - **VFS URI Dispatcher** (`lib/rails_ai_context/vfs.rb`) โ€” Pattern-matched routing for `rails-ai-context://` URIs. Resolves models, controllers, controller actions, views, and routes. Each call introspects fresh. Path traversal protection for view reads. - **4 Medium4/7/2026
v5.3.0 ### Added โ€” Phase 2: Cross-Tool Semantic Hydration (Ground Truth Engine Blueprint #38) Controller and view tools now automatically inject schema hints for referenced models, eliminating the need for follow-up tool calls. - **SchemaHint** (`lib/rails_ai_context/schema_hint.rb`) โ€” Immutable `Data.define` value object carrying model ground truth: table, columns, associations, validations, primary key, and `[VERIFIED]`/`[INFERRED]` confidence tag. - **HydrationResult** โ€” Wraps hints + warnings fMedium4/7/2026
v5.2.0 ### Added โ€” Phase 1: Prism AST Foundation (Ground Truth Engine Blueprint #36) System-wide AST migration replacing all regex-based Ruby source parsing with Prism AST visitors. This is the foundation layer for the Ground Truth Engine transformation (#37). - **AstCache** (`lib/rails_ai_context/ast_cache.rb`) โ€” Thread-safe Prism parse cache backed by `Concurrent::Map`. Keyed by path + SHA256 content hash + mtime. Invalidates automatically on file change. Shared by all AST-based introspectors. - Medium4/7/2026
v5.1.0 ### Fixed Accuracy fixes across 8 introspectors, eliminating false positives and capturing previously-missed signals. No public API changes; all 38 MCP tools retain their contracts. - **ApiIntrospector** โ€” pagination detection (`detect_pagination`) was substring-matching Gemfile.lock content, producing false positives on gems that merely contain the strategy name: `happypagy`, `kaminari-i18n`, transitive `pagy` dependencies. Now uses anchored lockfile regex (`^ pagy \(`) that only matches Medium4/5/2026
v5.0.0 ### Removed (BREAKING) This release removes the Design & Styling surface and the Accessibility rule surface. When AI assistants consumed pre-digested design/styling context (color palettes, Tailwind class strings, canonical HTML/ERB snippets), they produced poor UI/UX output by blindly copying class strings instead of understanding visual hierarchy. The accessibility surface was asymmetric (Claude-only static rule file, no live MCP tool) and provided generic best-practice rules that didn't earMedium4/5/2026
v4.7.0 ### Added - **Anti-Hallucination Protocol** โ€” 6-rule verification section embedded in every generated context file (CLAUDE.md, AGENTS.md, .claude/rules/, .cursor/rules/, .github/instructions/, copilot-instructions.md). Targets specific AI failure modes: statistical priors overriding observed facts, pattern completion beating verification, inheritance blindness, empty-output-as-permission, stale-context-lies. Rules force AI to verify column/association/route/method/gem names before writing, markMedium4/5/2026
v4.6.0 ### Added - **Integration test suite** โ€” 3 purpose-built Rails 8 apps exercising every gem feature end-to-end: - `full_app` โ€” comprehensive app (38 gems, 14 models, 15 controllers, 26 views, 5 jobs, 3 mailers, multi-database, ViewComponent, Stimulus, STI, polymorphic, AASM, PaperTrail, FriendlyId, encrypted attributes, CurrentAttributes, Flipper feature flags, Sentry monitoring, Pundit auth, Ransack search, Dry-rb, acts_as_tenant, Docker, Kamal, GitHub Actions CI, RSpec + FactoryBot) - `apiMedium4/4/2026
v4.5.2 ### Added - **Strong params permit list extraction** โ€” Controller introspector now parses `params.require(:x).permit(...)` calls, returning structured hashes with `requires`, `permits`, `nested`, `arrays`, and `unrestricted` fields. Handles multi-line chains, hash rocket syntax, and `params.permit!` detection - **N+1 risk levels** โ€” PerformanceCheck now classifies N+1 risks as `[HIGH]` (no preloading), `[MEDIUM]` (partial preloading), or `[low]` (already preloaded). Detects loop patterns in conMedium4/4/2026
v4.5.1Release v4.5.1. See [CHANGELOG.md](CHANGELOG.md) for details.Medium4/3/2026
v4.5.0Release v4.5.0. See [CHANGELOG.md](CHANGELOG.md) for details.Medium4/3/2026
v4.4.0 ### Added - **33 introspector enhancements** โ€” every introspector upgraded with new detection capabilities: - **SchemaIntrospector**: expression indexes, column comments in static parse, `change_column_default`/`change_column_null` in migration replay - **ModelIntrospector**: STI hierarchy detection (parent/children/type column), `attribute` API, enum `_prefix:`/`_suffix:`, `after_commit on:` parsing, inline `private def` exclusion - **RouteIntrospector**: route parameter extraction, rootMedium4/3/2026
v4.3.3 ### Fixed - **100 bare rescue statements across 46 files** โ€” all replaced with `rescue => e` + conditional debug logging (`$stderr.puts ... if ENV["DEBUG"]`); errors are now visible instead of silently swallowed - **database_stats introspector orphaned** โ€” `DatabaseStatsIntrospector` was unreachable (not in any preset); added to `:full` preset (32 โ†’ 33 introspectors) - **CHANGELOG date errors** โ€” v4.0.0 corrected from 2026-03-26 to 2026-03-27, v4.2.0 from 2026-03-26 to 2026-03-30 (verified agaiMedium4/2/2026
v4.3.2 ### Fixed - **review_changes undefined variable** โ€” `changed_tests` (NameError at runtime) replaced with correct `test_files` variable in `detect_warnings` - **N+1 introspector O(n*m*k) view scan** โ€” `detect_n_plus_one` now pre-loads all view file contents once via `preload_view_contents` instead of re-globbing per model+association pair - **atomic write collision** โ€” temp filenames now include `SecureRandom.hex(4)` suffix to prevent concurrent process collisions on the same file - **bare rescuMedium4/2/2026
v4.3.1 ### Fixed - **performance_check false positives** โ€” now parses `t.index` inside `create_table` blocks (was only parsing `add_index` outside blocks, missing inline indexes) - **review_changes overflow** โ€” capped at 20 files with 30 diff lines each; remaining files listed without diff to prevent 200K+ char responses - **get_context ivar cross-check** โ€” now follows `render :other_template` references (create rendering :new on failure no longer shows false positives) - **generate_test setup block**Medium4/2/2026
v4.3.0 ### Added - **`rails_onboard`** โ€” narrative app walkthrough (quick/standard/full) for new developers and AI agents: stack, data model, authentication, key flows, jobs, frontend, testing, getting started - **`rails_generate_test`** โ€” generates test scaffolding matching project patterns: detects framework (RSpec/Minitest), factories vs fixtures, assertion style, Devise helpers; covers validations, associations, scopes, enums, request specs with routes - **`rails_diagnose`** โ€” one-call error diagnMedium4/1/2026
v4.2.3 ### Fixed - **Unicode output** โ€” `rails_get_context` ivar cross-check now renders actual Unicode symbols (โœ“โœ—โš ) instead of literal `\u2713` escape sequences - **Scope name rendering** โ€” all 6 serializers (claude, cursor, copilot, opencode, claude_rules, copilot_instructions) now extract scope names from hash-style scope data instead of dumping raw `{:name=>"active", :body=>"..."}` into output - **Scope exclusion** โ€” `ModelIntrospector#extract_public_class_methods` now correctly extracts scope naMedium4/1/2026
v4.2.2 ### Fixed - **Vite config detection** โ€” framework plugin detection now checks `.mts`, `.mjs`, `.cts`, `.cjs` extensions in addition to `.ts` and `.js` - **Component catalog ERB** โ€” no-props no-slots components now generate inline `<%= render Foo.new %>` instead of misleading `do...end` block - **Custom tools validation** โ€” invalid entries in `config.custom_tools` are now filtered with a clear warning instead of crashing the MCP server with a cryptic `NoMethodError` ### Changed - Test count: 99Medium4/1/2026
v4.2.1 ### Fixed - **Security: SQL comment stripping** โ€” `rails_query` now strips MySQL-style `#` comments in addition to `--` and `/* */` - **Security: Regex injection** โ€” PerformanceIntrospector now uses `Regexp.escape` on all interpolated model/association names to prevent regex injection - **Security: SearchDocs error memoization** โ€” transient index load failures (JSON parse errors, missing file) are no longer cached permanently; subsequent calls retry instead of returning stale errors - **SecuritMedium3/31/2026
v4.2.0 ### Added - New `rails_search_docs` tool: bundled topic index with weighted keyword search, on-demand GitHub fetch for Rails documentation - New `rails_query` tool: safe read-only SQL queries with defense-in-depth (regex pre-filter + SET TRANSACTION READ ONLY + configurable timeout + row limit + column redaction) - New `rails_read_logs` tool: reverse file tail with level filtering (debug/info/warn/error/fatal) and sensitive data redaction - New config options: `query_timeout` (default timeout fMedium3/30/2026
v4.1.0 ### Added - New `rails_get_frontend_stack` tool: detects React/Vue/Svelte/Angular, Inertia/react-rails mounting, state management, TypeScript config, monorepo layout, package manager - New `FrontendFrameworkIntrospector`: parses package.json (JSON.parse with BOM-safe reading), config/vite.json, config/shakapacker.yml, tsconfig.json - Frontend framework detection covers patterns 3 (hybrid SPA), 4 (API+SPA), and 7 (Turbo Native) - API introspector: OpenAPI/Swagger spec detection, CORS config parsMedium3/28/2026
v4.0.0 ### Added - 4 new MCP tools: `rails_get_component_catalog`, `rails_performance_check`, `rails_dependency_graph`, `rails_migration_advisor` - 3 new introspectors: ComponentIntrospector (ViewComponent/Phlex), AccessibilityIntrospector (ARIA/a11y), PerformanceIntrospector (N+1/indexes) - ViewComponent/Phlex component catalog: props, slots, previews, sidecar assets, usage examples - Accessibility scanning: ARIA attributes, semantic HTML, screen reader text, alt text, landmark roles, accessibility Medium3/27/2026
v3.1.0 ### Fixed - **Consistent input normalization across all tools** โ€” AI agents and humans can now use any casing or format and tools resolve correctly: - `model=brand_profile` (snake_case) now resolves to `BrandProfile` via `.underscore` comparison in `get_model_details`. - `table=Cook` (model name) now resolves to `cooks` table via `.underscore.pluralize` normalization in `get_schema`. - `controller=CooksController` now works in `get_view` and `get_routes` โ€” both strip `Controller`/`_contrMedium3/26/2026
v3.0.1Release v3.0.1. See [CHANGELOG.md](CHANGELOG.md) for details.Medium3/26/2026
v3.0.0## v3.0.0 โ€” CLI Tools + Windsurf Removal ### Breaking Changes **Windsurf support removed.** v2.0.5 is the last version with Windsurf support. If you need Windsurf context files, pin your Gemfile: ```ruby gem "rails-ai-context", "~> 2.0" ``` ### New: CLI Tool Support โ€” The Game Changer All 25 introspection tools now work directly from the terminal. No MCP server needed. ```bash rails 'ai:tool[schema]' table=users detail=full rails 'ai:tool[search_code]' pattern="can_cook?" match_type=trace Medium3/26/2026
v2.0.5 ### Changed - **Task-based MCP tool instructions** โ€” all 6 serializers (Claude, Cursor, Copilot, Windsurf, OpenCode) rewritten from tool-first to task-first: "What are you trying to do?" โ†’ exact tool call. 7 task categories: understand a feature, trace a method, add a field, fix a controller, build a view, write tests, find code. Every AI agent now understands which tool to use for any task. - **Concern detail:"full" bug fix** โ€” `\b` after `?`/`!` prevented 13 of 15 method bodies from being exMedium3/25/2026
v2.0.4 ### Added - **Orphaned table detection** โ€” `get_schema` standard mode flags tables with no ActiveRecord model: "โš  Orphaned tables: content_calendars, cook_comments" - **Concern method source code** โ€” `get_concern(name:"X", detail:"full")` shows method bodies inline, same pattern as callbacks tool. - **analyze_feature: inherited filters** โ€” shows `authenticate_user! (from ApplicationController)` in controller section. - **analyze_feature: code-ready route helpers** โ€” `cook_path(@record)`, `cookMedium3/25/2026
v2.0.3 ### Added - **Trace mode 100%** โ€” `match_type:"trace"` now shows 7 sections: definition with class/module context, source code, internal calls, sibling methods (same file), app callers with route chain hints, and test coverage (separated from app code). Zero follow-up calls needed. - **README rewrite** โ€” neuro marketing techniques: loss aversion hook, measured token savings table, trace output inline, architecture diagram. 456โ†’261 lines.Medium3/25/2026
v2.0.2 ### Added - **`match_type:"trace"` in search_code** โ€” full method picture in one call: definition + source code + all callers grouped by type (Controller/Model/View/Job/Service/Test) + internal calls. The game changer for code navigation. - **`match_type:"call"`** โ€” find call sites only, excluding definitions. - **Smart result limiting** โ€” <10 shows all, 10-100 shows half, >100 caps at 100. Pagination via `offset:` param. - **`exclude_tests:true`** โ€” skip test/spec/features directories in searMedium3/25/2026
v2.0.1 ### Fixed - **MCP-first mandatory workflow in all serializers** โ€” all 6 serializer outputs (Claude, Cursor, Copilot, Windsurf, OpenCode) now use "MANDATORY, Use Before Read" language with structured workflow, anti-patterns table, and "Do NOT Bypass" rules. AI agents are explicitly instructed to never read reference files directly. - **27 type-safety bugs in serializers** โ€” fixed `.keys` called on Array values (same pattern as #14) across `design_system_helper.rb`, `get_design_system.rb`, `markMedium3/25/2026
v2.0.0 ### Added - **9 new MCP tools (16โ†’25)** โ€” `rails_get_concern` (concern methods + includers), `rails_get_callbacks` (execution order + source), `rails_get_helper_methods` (app + framework helpers + view refs), `rails_get_service_pattern` (interface, deps, side effects), `rails_get_job_pattern` (queue, retries, guards, broadcasts), `rails_get_env` (env vars, credentials keys, external services), `rails_get_partial_interface` (locals contract + usage), `rails_get_turbo_map` (stream/frame wiring +Medium3/25/2026
v1.2.1 ### Fixed - **New models now discovered via filesystem fallback** โ€” when `ActiveRecord::Base.descendants` misses a newly created model, the introspector scans `app/models/*.rb` and constantizes them. Fixes model invisibility until MCP restart. - **Devise meta-methods no longer fill class/instance method caps** โ€” filtered 40+ Devise-generated methods (authentication_keys=, email_regexp=, password_required?, etc.). Source-defined methods now prioritized over reflection-discovered ones. - **ContrMedium3/23/2026
v1.2.0 ### Added - **Design system extraction** โ€” ViewTemplateIntrospector now extracts canonical page examples (real HTML/ERB snippets from actual views), full color palette with semantic roles (primary/danger/success/warning), typography scale (sizes, weights, heading styles), layout patterns (containers, grids, spacing scale), responsive breakpoint usage, interactive state patterns (hover/focus/active/disabled), dark mode detection, and icon system identification. - **New MCP tool: `rails_get_desiMedium3/23/2026
v1.1.1 ### Added - **Full-preset stack overview in all serializers** โ€” compact mode now surfaces summary lines for auth, Hotwire/Turbo, API, I18n, ActiveStorage, ActionText, assets, engines, and multi-database in generated context files (CLAUDE.md, AGENTS.md, .windsurfrules, and all split rules). Previously this data was only available via MCP tools. - **`rails_analyze_feature` in all tool reference sections** โ€” the 14th tool (added in v1.0.0) was missing from serializer output. Now listed in all genMedium3/23/2026
v1.1.0 ### Changed - **Default preset changed to `:full`** โ€” all 28 introspectors now run by default, giving AI assistants richer context out of the box. Introspectors that don't find relevant data return empty hashes with zero overhead. Use `config.preset = :standard` for the previous 13-core default.Medium3/23/2026
v1.0.0 ### Added - **New composite tool: `rails_analyze_feature`** โ€” one call returns schema + models + controllers + routes for a feature area (e.g., `rails_analyze_feature(feature:"authentication")`). Total MCP tools: 14. - **Custom tool registration API** โ€” `config.custom_tools << MyCompany::PolicyCheckTool` lets teams extend the MCP server with their own tools. - **Structured error responses with fuzzy suggestions** โ€” `not_found_response` helper in BaseTool with "Did you mean?" fuzzy matching (suMedium3/23/2026
v0.15.10 ### Changed - **Gemspec description rewritten** โ€” repositioned from feature list to value proposition: mental model, semantic validation, cross-file error detection.Medium3/23/2026
v0.15.9 ### Added - **Deep diagnostic checks in `rails ai:doctor`** โ€” upgraded from 13 shallow file-existence checks to 20 deep checks: pending migrations, context file freshness, .mcp.json validation, introspector health (dry-runs each one), preset coverage (detects features not in preset), .env/.master.key gitignore check, auto_mount production warning, schema/view size vs limits.Medium3/23/2026
v0.15.8 ### Added - **Semantic validation (`level:"rails"`)** โ€” `rails_validate` now supports `level:"rails"` for deep semantic checks beyond syntax: partial existence, route helper validity, column references vs schema, strong params vs schema columns, callback method existence, route-action consistency, `has_many` dependent options, missing FK indexes, and Stimulus controller file existence.Medium3/23/2026
v0.15.7 ### Improved - **Hybrid filter extraction** โ€” controller filters now use reflection for complete names (handles inheritance + skips), with source parsing from the inheritance chain for only/except constraints. - **Callback source fallback** โ€” when reflection returns nothing (e.g. CI), falls back to parsing callback declarations from model source files. - **ERB validation accuracy** โ€” in-process compilation with `<%=` โ†’ `<%` pre-processing and yield wrapper eliminates false positives from blockLow3/22/2026
v0.15.6 ### Added - **7 new configurable options** โ€” `excluded_controllers`, `excluded_route_prefixes`, `excluded_concerns`, `excluded_filters`, `excluded_middleware`, `search_extensions`, `concern_paths` for stack-specific customization. - **Configurable file size limits** โ€” `max_file_size`, `max_test_file_size`, `max_schema_file_size`, `max_view_total_size`, `max_view_file_size`, `max_search_results`, `max_validate_files` all exposed via `Configuration`. - **Class methods in model detail** โ€” `rails_Low3/22/2026
v0.15.5 ### Fixed - **ERB validation** โ€” now catches missing `<% end %>` by compiling ERB to Ruby then syntax-checking the result (was only checking ERB tag syntax). - **Controller namespace format** โ€” accepts both `Bonus::CrisesController` and `bonus/crises` (cross-tool consistency). - **Layouts discoverable** โ€” `controller:"layouts"` now works in view tool. - **Validate error detail** โ€” Ruby shows up to 5 error lines, JS shows 3 (was truncated to 1). - **Invalid/empty regex** โ€” early validation withLow3/22/2026
v0.15.4 ### Fixed - **View subfolder paths** โ€” listings now show full relative paths (`bonus/brand_profiles/index.html.erb`) instead of just basenames. - **Controller flexible matching** โ€” `"cooks"`, `"CooksController"`, `"cookscontroller"` all resolve (matches other tools' forgiving lookup). - **View path traversal** โ€” explicit `..` and absolute path rejection before any filesystem operation. - **Schema case-insensitive** โ€” table lookup now case-insensitive (matches models/routes/etc.). - **limit:0 sLow3/22/2026

Dependencies & License Audit

Loading dependencies...

Similar Packages

toolhive-studioToolHive is an application that allows you to install, manage and run MCP servers and connect them to AI agentsv0.36.0
@tankpkg/mcp-serverMCP server for Tank - scan and publish AI agent skills from your editorv0.16.2
llm-wikiLLM-powered knowledge base from your Claude Code, Codex CLI, Copilot, Cursor & Gemini sessions. Karpathy's LLM Wiki pattern โ€” implemented and shipped.v1.3.82
windbackAI agent session viewer and unified session workspace1.0.6
codebase-contextGenerate a map of your codebaseto help AI Agents understand your architecture, coding conventions and patterns. Discoverable with Semantic Searchv2.3.0

More in MCP Servers

AstrBotAgentic IM Chatbot infrastructure that integrates lots of IM platforms, LLMs, plugins and AI feature, and can be your openclaw alternative. โœจ
agentscopeBuild and run agents you can see, understand and trust.
claude-plugins-officialOfficial, Anthropic-managed directory of high quality Claude Code Plugins.
langchain4jLangChain4j is an open-source Java library that simplifies the integration of LLMs into Java applications through a unified API, providing access to popular LLMs and vector databases. It makes impleme