rails-ai-context
rails-ai-context
Дайте вашему ИИ-ассистенту по коду достоверные данные о вашем Rails-приложении
:star: Если этот гем сэкономил вам цикл исправлений, поставьте звезду на GitHub!
Зачем • Возможности • Начало работы • Использование • Инструменты • Конфигурация • Документация

rails-ai-context — это Ruby-гем, который превращает ваше Rails-приложение в источник истины для ИИ-ассистентов по коду. Вместо того чтобы угадывать вашу схему, ассоциации, маршруты и соглашения по обучающим данным, ассистент спрашивает ваше приложение: 45 инструментов только для чтения, доступных через MCP или из CLI, плюс сгенерированные контекстные файлы для Claude Code, Cursor, GitHub Copilot, OpenCode и Codex CLI.
[!TIP] Ничего не нужно добавлять в Gemfile, если не хотите.
gem install rails-ai-context, затемrails-ai-context initвнутри любого Rails-приложения. Он также работает с приложением, которое не запускается: передайте--no-boot, и каждый инструмент будет отвечать на основе исходных файлов.
Зачем
Вы видели, как ваш ассистент делает следующее:
Пишет миграцию для колонки, которая уже существует.
Вызывает
user.posts, когда ассоциация —user.articles.Генерирует тесты с FactoryBot в наборе, основанном на фикстурах.
Пропускает
before_action, унаследованный от родительского контроллера, а затем удивляется, почему не работает аутентификация.Добавляет гем, который у вас уже есть, или вызывает API из того, которого нет.
Выдумывает метод, которого нет в кодовой базе.
Вы замечаете это, исправляете, повторяете запрос, и что-то рядом ломается. Токены дёшевы; цикл исправлений — вот что стоит вам полдня. Этот гем устраняет догадки в самом источнике.
Вы просите ИИ... | Без | С |
Добавить колонку | Пишет миграцию, дублируя существующую колонку | Читает живую схему, видит |
Вызвать | Угадывает; | Определяет реальную ассоциацию из модели |
Написать тесты для новой модели | Генерирует с FactoryBot | Определяет ваш набор на фикстурах и подстраивается |
Исправить падающий create action | Пропускает унаследованный | Получает фильтры родительского контроллера вместе с исходником действия |
Собрать страницу дашборда | Выдумывает классы Tailwind по памяти | Получает ваши реальные паттерны кнопок/карточек/алертов |
Проследить, где используется | Читает 6 файлов подряд и всё равно пропускает вызывающие места | Один вызов: определение + исходник + все вызывающие + тесты |

Related MCP server: Synapse
Возможности
45 инструментов только для чтения для схемы, моделей, контроллеров, маршрутов, представлений, Stimulus, Turbo, задач, сервисов, почтовиков, i18n, гемов, конфигурации, тестов, безопасности, производительности и многого другого. Каждый ответ исходит из вашего приложения.
Разбор Prism AST для интроспекции моделей. Каждый результат несёт
[VERIFIED]или[INFERRED], чтобы ассистент знал, что является достоверным фактом, а что требует проверки в рантайме.Три способа подключения: MCP через stdio, MCP, встроенный в ваше Rails-приложение через HTTP, или обычный CLI в любом терминале.
Сгенерированные контекстные файлы для Claude Code, Cursor, GitHub Copilot, OpenCode и Codex CLI, с конфигурацией MCP, которую каждый инструмент автоматически определяет при открытии проекта.
Живые ресурсы: URI
rails://иrails-ai-context://, которые выполняют интроспекцию заново при каждом чтении.Правила против галлюцинаций, включённые в каждый сгенерированный контекстный файл, по умолчанию активны.
Статический уровень: когда приложение не может запуститься, инструменты отвечают на основе
config/routes.rb,db/schema.rb, миграций и исходных файлов и сообщают об этом.Работает с реальными структурами приложений: пакеты packwerk, движки внутри репозитория, дампы схем нескольких баз данных, Mongoid, API-only приложения.
Пользовательские инструменты: регистрируйте собственные классы
MCP::Toolрядом со встроенными и тестируйте их с помощью встроенногоTestHelper.
Начало работы
Требования
Ruby 3.1 или новее
Rails 7.0 или новее
Необязательно:
brakemanдляsecurity_scan,listenдляwatch,ripgrepдля более быстрогоsearch_code
Установка в Gemfile
bundle add rails-ai-context --group development
rails generate rails_ai_context:installГенератор спрашивает, какие ИИ-инструменты вы используете и нужен ли режим MCP или CLI, затем записывает контекстные файлы, конфигурацию MCP для каждого инструмента и config/initializers/rails_ai_context.rb. Повторный запуск безопасен: он сохраняет то, что у вас есть, и добавляет недостающее.
Установка отдельно
gem install rails-ai-context
cd your-rails-app
rails-ai-context init
rails-ai-context serveБез изменений в Gemfile. Конфигурация хранится в .rails-ai-context.yml. Работает с rbenv, rvm, asdf, mise, chruby и системным Ruby. См. Standalone.
Проверка работы
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Затем откройте проект в вашем ИИ-инструменте. Записанная конфигурация MCP подхватывается при открытии, и ассистент начинает вызывать rails_get_model_details вместо угадывания.
[!NOTE] Команды CLI выше — для вас. Когда MCP подключён, ассистент сам вызывает те же инструменты; вам не нужно их вводить.
Использование
MCP через stdio
По умолчанию. Каждый ИИ-инструмент получает собственный конфигурационный файл (.mcp.json, .cursor/mcp.json, .vscode/mcp.json, opencode.json, .codex/config.toml), указывающий на:
rails ai:serve # in-Gemfile
rails-ai-context serve # standaloneMCP через HTTP
Смонтируйте сервер внутри вашего приложения. Он наследует ваши маршруты, аутентификацию и middleware и не требует второго процесса.
# config/routes.rb
mount RailsAiContext::Engine, at: "/mcp"Направьте клиент на http://localhost:3000/mcp. Также есть отдельный HTTP-процесс: rails-ai-context serve --transport http --port 6029.
[!WARNING] Каждый подключённый клиент, открывший SSE-канал, удерживает один поток сервера на время жизни соединения. Для разработки это нормально; увеличьте число потоков Puma или используйте отдельный HTTP-процесс, если несколько клиентов используют приложение.
CLI
Те же 45 инструментов, без сервера, в любом терминале.
rails 'ai:tool[search_code]' pattern="publishable?" match_type=trace
rails-ai-context tool schema --table users --detail fullИмена инструментов распознаются гибко: schema, get_schema и rails_get_schema — все работают. Большинство инструментов принимают detail=summary|standard|full.
Команды
В Gemfile | Standalone | Что делает |
|
| Запустить MCP-сервер (stdio) |
|
| Запустить MCP-сервер (HTTP) |
|
| Запустить один инструмент |
|
| Список инструментов |
|
| Сгенерировать контекстные файлы |
|
| Диагностика и оценка готовности |
|
| Перегенерировать при изменении файлов |
|
| Запустить пресет из нескольких инструментов ( |
Флаги, общие для команд чтения приложения: --app-path PATH для указания другой директории, --environment ENV для установки RAILS_ENV и --no-boot для пропуска попытки запуска и ответа на основе исходников. Полный список в справочнике CLI.
Инструменты
Каждый инструмент только для чтения и отвечает на основе вашего приложения.
Категория | Инструменты |
Поиск и трассировка |
|
Понимание |
|
Схема и модели |
|
Контроллеры и маршруты |
|
Представления и фронтенд |
|
Тестирование и качество |
|
Конфигурация приложения и сервисы |
|
Данные и отладка |
|
Несколько полезных в первый же день:
search_codeсmatch_type=traceвозвращает определение, исходный код, всех вызывающих, сгруппированных по типу, и тесты — одним вызовом. Это заменяет 4–5 чтений файлов.get_controllersвозвращает исходный код действий с унаследованными фильтрами, strong params и картой рендеринга.get_model_detailsвозвращает ассоциации, валидации, области видимости, перечисления и макросы из AST, каждый помечен как[VERIFIED]или[INFERRED].queryвыполняет SQL только для чтения с таймаутом, лимитом строк и редактированием столбцов.read_logsредактирует чувствительные данные до того, как они покинут процесс.
Параметры для всех 45 инструментов — в справочнике по инструментам; рабочие примеры — в рецептах.
Живые ресурсы
MCP-клиенты также могут читать структурированные данные как ресурсы. Шаблоны выполняют интроспекцию заново при каждом запросе:
URI | Возвращает |
| Ассоциации, валидации, схему для одной модели |
| Действия, унаследованные фильтры, параметры |
| Исходный код действия с применяемыми фильтрами |
| Содержимое шаблона представления (обход пути заблокирован) |
| Живая карта маршрутов для одного контроллера |
Плюс 9 статических ресурсов: rails://schema, routes, conventions, gems, controllers, config, tests, migrations, engines.
Правила против галлюцинаций
Каждый сгенерированный файл контекста (CLAUDE.md, .cursor/rules/, .github/instructions/, AGENTS.md) поставляется с шестью правилами, которые ассистент читает перед написанием кода:
Проверяй перед тем, как писать. Никогда не ссылайся на столбец, ассоциацию, маршрут, хелпер, метод, класс, партиал или гем, которые не были подтверждены вызовом инструмента в этом ходе.
Помечай каждое предположение как
[ASSUMPTION]. «Мне нужно сначала проверить X» — хороший ответ.Обучающие данные описывают средний Rails. Это приложение не среднее. Когда что-то кажется очевидно стандартным, всё равно запрашивай.
Проверяй цепочку наследования перед каждым изменением: унаследованные фильтры, concerns, includes, STI-родители.
Пустой вывод инструмента — это информация. «0 вызывающих найдено» означает «расследуй», а не «продолжай».
Устаревший контекст лжёт. Перезапрашивай после записи.
Включено по умолчанию. Отключи с помощью config.anti_hallucination_rules = false, если предпочитаешь свои правила.
Когда приложение не может загрузиться
rails-ai-context пытается выполнить полную загрузку для живой рефлексии. Когда загрузка не удаётся (отсутствуют переменные окружения, недоступный сервис, сломанный инициализатор), команды чтения приложения переключаются на статический уровень вместо того, чтобы умереть: маршруты из config/routes.rb, схема из db/schema.rb, db/structure.sql или миграций, модели и контроллеры из их исходных файлов. Каждый ответ несёт баннер с указанием деградации, статические данные помечены [STATIC], а разделы, которым нужна загруженная загрузка, сообщают [UNAVAILABLE] с причиной.
--no-boot полностью пропускает попытку, что быстро и невосприимчиво к побочным эффектам загрузки. doctor всё ещё требует загружаемое приложение; диагностика загрузки — его работа.
Код находится в стандартной структуре, в пакетах packwerk (packs/*/app/*), в движках внутри репозитория (engines/*/app/*) и в любых extra_app_paths из .rails-ai-context.yml. Дампы схемы для нескольких баз данных (db/queue_schema.rb и подобные) отображаются в разделе Secondary databases. Приложения на Mongoid получают сигнал схемы [UNAVAILABLE] плюс статические данные модели вместо пустой таблицы, а приложения только с API получают «не применимо» от инструментов представления и фронтенда вместо тихого пустого места. Подробности в Совместимость.
Конфигурация
# 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Автономные установки используют те же ключи в .rails-ai-context.yml. Все параметры с значениями по умолчанию — в Конфигурация.
Пользовательские инструменты
Зарегистрируй свои собственные инструменты рядом со встроенными:
# 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"]Протестируй их с помощью встроенного помощника (RSpec или Minitest):
include RailsAiContext::TestHelper
response = execute_tool("business_metrics", period: "month")
assert_tool_response_includes(response, "Users")См. Пользовательские инструменты.
Наблюдаемость
Каждый вызов MCP запускает событие ActiveSupport::Notifications:
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Как это работает
graph TD
A["Your Rails app\nmodels + schema + routes + controllers + views + jobs"] -->|"40 introspectors"| B
B["rails-ai-context\nPrism AST · cached · confidence-tagged\nstatic tier when the app can't boot"]
B --> C["MCP server\nstdio / HTTP\n45 tools · 5 templates · 9 resources"]
B --> D["CLI\nrake / Thor\nsame 45 tools"]
B --> E["Context files\nCLAUDE.md · .cursor/rules/ · .github/instructions/ · AGENTS.md"]
style A fill:#4a9eff,stroke:#2d7ad4,color:#fff
style B fill:#2d2d2d,stroke:#555,color:#fff
style C fill:#0984e3,stroke:#0770c2,color:#fff
style D fill:#00cec9,stroke:#00b5b0,color:#fff
style E fill:#a29bfe,stroke:#8c83f0,color:#fffВнутренности, список интроспекторов и AST-движок — в Архитектура и Интроспекторы.
Документация
Запуск за 5 минут | |
Каждая команда, параметр и опция | |
Все 45 инструментов с каждым параметром | |
Реальные рабочие процессы, от начала до конца | |
Claude Code, Cursor, Copilot, OpenCode, Codex CLI, HTTP-транспорт | |
Синтаксис команд, флагов и аргументов | |
Использование без записи в Gemfile | |
Каждая опция с её значением по умолчанию | |
Создание и тестирование собственных инструментов | |
Системный дизайн и внутренности | |
Все 40 интроспекторов и AST-движок | |
Уровни защиты SQL и блокировка файлов | |
Поддерживаемые версии, уровни работы, матрица форм приложений | |
Частые проблемы и их решения | |
Часто задаваемые вопросы |
Создано Rails-разработчиком с 10+ годами опыта в продакшене. Если это экономит твоё время, рассмотри спонсирование проекта.
Available Tools
35 toolsrails_analyze_featureARead-onlyIdempotent
Full-stack feature analysis: models, controllers, routes, services, jobs, views, Stimulus controllers, tests, related models, callbacks, concerns, and environment dependencies. Use when: exploring an unfamiliar feature, onboarding to a codebase area, or tracing a feature across layers. Pass feature:"authentication" or feature:"User" for broad cross-cutting discovery.
Inputs: feature (required).
rails_dependency_graphARead-onlyIdempotent
Generates a dependency graph showing how models connect through their associations. Output as Mermaid diagram syntax or plain text. Use when: understanding feature architecture, tracing data flow, planning refactors. Key params: model (center graph on model), depth (1-3), format (mermaid/text).
Inputs: depth, model, format, show_sti, +1 more.
rails_diagnoseARead-only
One-call error diagnosis: parses the error, classifies it, gathers controller/model/schema context, shows recent git changes, pulls relevant logs, and suggests a fix. Use when: you hit an error and need to understand why. Key params: error (required - paste the error message), file, line, action (controller#action).
Inputs: error (required), file, line, action.
rails_generate_testARead-onlyIdempotent
Generate test scaffolding that matches your project's actual test patterns - framework, factories, assertion style. Use when: adding tests for a model, controller, or service. Generates copy-paste-ready test files. Key params: model (e.g. 'User'), controller (e.g. 'PostsController'), file (e.g. 'app/services/foo.rb').
Inputs: file, type, model, controller.
rails_get_callbacksARead-onlyIdempotent
Get ActiveRecord model callbacks grouped by type, in Rails event order: before/after/around for validation, save, create, update, destroy. Use when: understanding side effects, debugging callback chains, or checking what happens on save/create/destroy. Specify model:"User" for one model's callbacks. detail:"full" includes callback method source code. The list is what the model, its base classes and its concerns declare, and within one type the order is the order Rails runs them, a before_ or around_ callback with prepend: true first, and after_commit in the order the app's setting gives.
Inputs: model, detail.
rails_get_component_catalogARead-onlyIdempotent
Returns ViewComponent and Phlex component catalog: props, slots, previews, which views render each component. Use when: building views with components, understanding component API, finding reusable components. Key params: component (filter by name), detail level.
Inputs: limit, detail, offset, component.
rails_get_concernARead-onlyIdempotent
Get ActiveSupport::Concern details: public methods, included modules, and which models/controllers include it. Use when: understanding shared behavior, checking concern interfaces, or finding where a concern is used. Specify name:"Searchable" for full detail, or omit for a list of all concerns. Filter with type:"model" or type:"controller".
Inputs: name, type, detail.
rails_get_configARead-onlyIdempotent
Get the app's configuration, one section per call. section: app (default: database, auth, assets, cache, session, queue, Action Cable, middleware, initializers), gems (notable gems by category), frontend (JS framework, build tool, TypeScript, package manager), api (serializers, GraphQL, versioning, CORS, rate limiting, pagination), engines (mounted engines and Rack apps), conventions (architecture and patterns), autoload (Zeitwerk paths, inflections), active_support (concerns, notifications, on_load hooks), env (names of environment variables and credentials keys), env_config (config/environments/*.rb per environment), i18n (locales, locale files, coverage).
Inputs: limit, detail, locale, offset, +3 more.
rails_get_contextARead-onlyIdempotent
Get cross-layer context in a single call - combines schema, model, controller, routes, views, stimulus, and tests. Use when: you need full context for implementing a feature or modifying an action. Specify controller:"PostsController" action:"create" to get everything for that action in one call.
Inputs: model, action, feature, include, +1 more.
rails_get_controllersARead-onlyIdempotent
Get controller details: actions, before_action filters, strong params, and parent class. Use when: adding/modifying controller actions, checking what filters apply, or reading action source code. Filter with controller:"PostsController", drill into action:"create" for source code with line numbers.
Inputs: limit, action, detail, offset, +1 more.
rails_get_edit_contextARead-onlyIdempotent
Get targeted code context for surgical edits: returns matching lines with surrounding code and line numbers. Use when: you need to edit a specific method or section without reading the entire file. Requires file:"app/models/user.rb" and near:"def activate" (or line:42) to locate the code region.
Inputs: file (required), line, near, context_lines.
rails_get_helper_methodsARead-onlyIdempotent
Get Rails helper modules: method signatures, the view helpers controllers declare with helper_method, framework helpers in use, and which views call each helper. Use when: finding available view helpers, checking what helper methods exist, or understanding shared view logic. Specify helper:"ApplicationHelper" for full detail, or omit to list all helpers with method counts.
Inputs: limit, detail, helper, offset.
rails_get_job_patternARead-onlyIdempotent
Analyze background jobs in app/jobs/, app/workers/ and app/sidekiq/: queues, retries, perform signatures, guards, and what they call. Use when: understanding job infrastructure, adding a new job, or tracing async workflows. Specify job:"SendWelcomeEmail" for full detail, or omit to list all jobs with queue names and retry config.
Inputs: job, detail.
rails_get_mailersARead-onlyIdempotent
Get ActionMailer mailers: every mailer class with its delivery actions, delivery method, own defaults, layout and callbacks, template formats per action and preview class, the queue deliver_later uses, interceptors and observers, and the Action Mailbox mailboxes with the routing that sends inbound mail to each. Use when: adding an email, checking which mailer sends what, or finding the action to preview/test. Filter with mailer:"UserMailer". Omit for all mailers.
Inputs: limit, mailer, offset.
rails_get_model_detailsARead-onlyIdempotent
Get ActiveRecord model details: associations, validations, scopes, enums, callbacks, concerns. Use when: understanding model relationships, adding validations, checking existing scopes/callbacks. Specify model:"User" for full detail, or omit for a list. detail:"full" shows association lists.
Inputs: limit, model, detail, offset.
rails_get_partial_interfaceARead-onlyIdempotent
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. Specify partial:"shared/status_badge" to see its full interface. Supports both underscore-prefixed and non-prefixed names.
Inputs: partial (required), detail.
rails_get_routesARead-onlyIdempotent
Get routing table: HTTP verbs, paths, controller#action, route names. Use when: building links/redirects, checking available endpoints, verifying route helpers exist. Filter with controller:"users", use detail:"summary" for counts or detail:"full" for route names.
Inputs: limit, detail, offset, app_only, +1 more.
rails_get_schemaARead-onlyIdempotent
Get database schema: tables, columns, types, indexes, foreign keys. Use when: writing migrations, checking column types/constraints, understanding table relationships. Filter to one table with table:"users", control detail with detail:"summary"|"standard"|"full".
Inputs: limit, table, detail, format, +1 more.
rails_get_service_patternARead-onlyIdempotent
Analyze service objects in app/services/, app/interactions/ and app/interactors/: patterns, interfaces, dependencies, and side effects. Use when: understanding how services are structured, adding a new service, or tracing what a service does. Specify service:"CreateOrder" for full detail, or omit to detect the common pattern and list all services.
Inputs: detail, service.
rails_get_stimulusARead-onlyIdempotent
Get Stimulus controllers: targets, values, actions, outlets, classes. Use when: wiring up data-controller attributes in views, adding targets/values, or checking existing Stimulus behavior. Filter with controller:"filter-form" for one controller's full API, or list all with detail:"summary".
Inputs: limit, detail, offset, controller.
rails_get_test_infoARead-onlyIdempotent
Get test infrastructure and existing test files: framework, factories, fixtures, CI config, coverage setup. Use when: writing new tests, checking what factories/fixtures exist, or finding the test file for a model/controller. Use model:"User" or controller:"Posts" to see existing tests. detail:"full" lists factory and fixture names.
Inputs: model, detail, controller.
rails_get_turbo_mapARead-onlyIdempotent
Map Turbo Streams and Frames across the app: model broadcasts, channel subscriptions, frame tags, and DOM target mismatches. Use when: debugging Turbo Stream delivery, adding real-time updates, or understanding broadcast→subscription wiring. Filter with stream:"notifications" for a specific stream, or controller:"messages" for one controller's Turbo usage.
Inputs: detail, stream, controller.
rails_get_viewARead-onlyIdempotent
Get view templates, partials, and their Stimulus/partial references. Use when: editing ERB views, checking which partials a page renders, or finding Stimulus controller usage. Filter with controller:"posts" for all views, or path:"posts/index.html.erb" for one file's content.
Inputs: path, detail, controller.
rails_migration_advisorARead-onlyIdempotent
Generates migration code for schema changes. Given an action (add_column, remove_column, rename_column, add_index, add_association, change_type), generates the migration, flags irreversible operations, and shows affected models. Use when: adding fields, changing schema, planning database changes. Key params: action, table, column, type, new_name (for rename_column).
Inputs: table (required), action (required), type, column, +2 more.
rails_onboardARead-onlyIdempotent
Get a narrative walkthrough of the Rails application - stack, data model, authentication, key flows, background jobs, frontend, testing, getting started instructions, and the app's custom rake tasks, generators and Railties. Use when: first encountering a project, onboarding a new developer, or orienting an AI agent. Key params: detail (summary/standard/full).
Inputs: detail.
rails_performance_checkARead-onlyIdempotent
Static analysis for Rails performance anti-patterns: N+1 query risks, missing counter_cache, Model.all in controllers, missing foreign key indexes, eager loading candidates. Use when: reviewing code for performance, before deploying, or investigating slow pages. Key params: model (filter by model), category (filter by issue type), detail level.
Inputs: model, detail, category.
rails_queryARead-only
Execute read-only SQL queries against the database. Use when: checking data patterns, verifying migrations, debugging data issues. Safety: SQL validation + database-level READ ONLY + statement timeout + row limit. Development/test only by default. Key params: sql (SELECT only), limit (default 100), format (table/csv).
Inputs: sql (required), limit, format, explain, +1 more.
rails_read_logsARead-only
Read recent log entries with level filtering and sensitive data redaction. Use when: debugging errors, checking recent activity, investigating failed requests. Key params: lines (default 50), level (ERROR/WARN/INFO/DEBUG/FATAL/all), file, search. Search matches the redacted line, so a filtered value cannot be searched for.
Inputs: file, level, lines, search.
rails_review_changesARead-only
PR/commit review context: shows changed files with relevant schema/model/route context per file, detects warnings (missing indexes, removed validations, changed associations, new routes without tests). Use when: reviewing changes before merging, understanding what a commit changed and its impact. Key params: ref (default 'HEAD' for uncommitted, or 'main', 'HEAD~3', commit SHA).
Inputs: ref, files.
rails_runtime_infoARead-only
Live runtime state: database connection pool, table sizes, pending migrations, cache stats, job queues. Use when: debugging performance, checking database health, verifying deployment state, or understanding infrastructure. Key params: detail (summary/standard/full), section (database/cache/jobs/connections).
Inputs: detail, section, database.
rails_search_codeARead-onlyIdempotent
Search the Rails codebase with smart modes. Use match_type:"trace" to see where a method is defined, who calls it, and what it calls - in one call. Use match_type:"definition" for definitions only, "call" for call sites only, "class" for class/module definitions. Requires pattern:"method_name". Narrow with path:"app/models" and file_type:"rb".
Inputs: pattern (required), path, limit, offset, +6 more.
rails_search_docsARead-onlyIdempotent
Search a bundled index of the Rails guides and the Turbo, Stimulus and Hotwire Native handbooks. Use when: you need to reference Rails conventions, API details, or best practices. Pass query:"active record callbacks" to find matching topics. Filter with source:"guides", "turbo", "stimulus" or "hotwire". Set fetch:true to retrieve full content from GitHub (cached 24h).
Inputs: query (required), fetch, limit, source.
rails_security_scanARead-onlyIdempotent
Run Brakeman static security analysis on Rails app. Use when: after editing controllers/models/views, reviewing code for vulnerabilities, or before deploying. Filter with files:["app/controllers/users_controller.rb"], set confidence:"high" to reduce noise.
Inputs: files, checks, detail, confidence.
rails_session_contextBRead-only
Track what you've already queried to avoid redundant calls. Use action:"status" to see what tools you've called, action:"summary" for a compressed recap, action:"reset" to clear session, or mark:"tool:param" to record a query. Helps maintain focus during long development sessions.
Inputs: mark, action.
rails_validateARead-onlyIdempotent
Validate syntax and semantics of Ruby, ERB, and JavaScript files in a single call. Use when: after editing files, before committing, to catch syntax errors and Rails-specific issues. Pass files:["app/models/user.rb"], use level:"rails" for semantic checks (missing partials, route helpers, column refs in validates/permit/callbacks).
Inputs: files (required), level.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 35 tools
Most tools map to a distinct Rails artifact (schema, routes, callbacks, mailers, jobs, stimulus, turbo), but several boundaries blur: rails_analyze_feature and rails_get_context both promise 'full-stack context in one call' across the same layers, and rails_get_context vs rails_get_edit_context differ only by a word while doing very different things. rails_onboard also overlaps with rails_get_config, and rails_get_model_details subsumes rails_get_callbacks. Descriptions are detailed enough that an agent can usually recover, but misselection is a real risk.
All names use a uniform rails_ prefix and snake_case verb_noun form, which is highly readable. The only inconsistency is the verb layer: a large get_* family coexists with bare verbs (analyze_feature, search_code, review_changes, query, validate, onboard), so the 'get' prefix is applied unevenly. Predictable overall, minor deviation.
35 tools is heavy, sitting above the comfortable 3-15 band, and a few are redundant (analyze_feature vs get_context, session_context as a meta-bookkeeping utility). However, the server targets an entire Rails application surface, so most tools do correspond to a genuine distinct artifact type. Borderline over-scoped rather than gratuitous.
Coverage is unusually broad: schema, models, controllers, routes, views, partials, helpers, services, jobs, mailers, Stimulus, Turbo, components, tests, migrations, config, logs, security and performance, plus read-only SQL and docs search. Minor gaps remain around authorization policies (Pundit/CanCan), ActiveStorage/ActionText attachments, and API/GraphQL schema introspection. No dead ends for the core read-and-understand workflow.
Maintenance
Related MCP Connectors
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
12 read-only MCP tools for AI communication rules, instruction linting & 25-model benchmarks.
Read-only AI coding tools for change verification, release readiness, capacity, and guidance.
Read-only MCP tools for AI agent discovery, structured resources, and NIULAI information.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceProvides MCP tools that help AI agents get their bearings in a codebase with unified SQL views over code, git, docs, and conversations, powered by DuckDB.6Apache 2.0
- FlicenseNot gradedqualityDmaintenanceProvides structural code intelligence via 26 MCP tools, enabling AI assistants to query code symbols, dependencies, and call graphs accurately without file-pasting.-
- AlicenseAqualityCmaintenanceEnables AI coding agents to efficiently explore codebases by providing structural outlines, module digests, symbol bodies, and AST-aware grep via MCP.413 npm1MIT

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