Architecture
How rails-ai-context is built, and why: its modules and the request lifecycle.
System overview
graph TD
subgraph app["Your Rails App"]
A["models + schema + routes + controllers + views + jobs + config"]
end
A -->|"40 introspectors"| gem
subgraph gem["rails-ai-context"]
direction TB
subgraph engine["Introspection Engine"]
direction LR
I["Introspectors\n40 modules\nPresets\nCached"]
AST["AST Engine\nPrism\n47 listeners\nConfidence tags"]
H["Hydration Layer\nSchema hints\ninjected into\ntool responses"]
end
engine --> R["Tool Registry\n35 tools auto-discovered via inherited\n+ custom_tools - skip_tools = active tools"]
end
R --> MCP
R --> CLI
R --> S
subgraph outputs["Output"]
direction LR
MCP["MCP Server\nstdio / HTTP\nResources\nVFS URIs"]
CLI["CLI Runner\nRake / Thor\nSame 35 tools\nNo server needed"]
S["Serializers\n20 modules\nStatic files\nPer-AI-tool"]
end
style app fill:#4a9eff,stroke:#2d7ad4,color:#fff
style gem fill:#2d2d2d,stroke:#555,color:#fff
style engine fill:#3a3a3a,stroke:#666,color:#fff
style outputs fill:#1a1a1a,stroke:#444,color:#fff
style I fill:#6c5ce7,stroke:#5a4bd1,color:#fff
style AST fill:#e17055,stroke:#c0392b,color:#fff
style H fill:#00b894,stroke:#00a381,color:#fff
style R fill:#fdcb6e,stroke:#f0b429,color:#333
style MCP fill:#0984e3,stroke:#0770c2,color:#fff
style CLI fill:#00cec9,stroke:#00b5b0,color:#fff
style S fill:#a29bfe,stroke:#8c83f0,color:#fff
Data flow
sequenceDiagram
participant AI as AI Assistant
participant MCP as MCP Server
participant TR as Tool Registry
participant Cache as Cache Layer
participant App as Rails App
AI->>MCP: rails_get_schema(table: "users")
MCP->>TR: resolve tool + execute
TR->>Cache: check introspection cache
alt cache hit (TTL + fingerprint valid)
Cache-->>TR: cached context
else cache miss
Cache->>App: introspect (40 modules)
App-->>Cache: structured data
Cache-->>TR: fresh context
end
TR-->>MCP: MCP::Tool::Response
MCP-->>AI: schema with columns, indexes, hints
Request lifecycle
flowchart LR
A[Tool Call] --> B{Registered?}
B -->|Yes| C{Cache Valid?}
B -->|No| E[ToolNotFoundError]
C -->|Hit| D[Return Cached]
C -->|Miss| F[Introspect]
F --> G[Cache Result]
G --> D
D --> H[Hydrate\nSchema Hints]
H --> I[Truncate\nmax_tool_response_chars]
I --> J[MCP::Tool::Response]
Core modules
Introspectors (lib/rails_ai_context/introspectors/)
40 modules that extract structured data from your Rails app. Each introspector:
- Subclasses
Introspectors::Base, which holds theapphandle and itsroot - Returns a Hash, and raises on failure:
Introspector#callturns a raised section into{ error: msg }and logs a warning, so one broken section costs only itself - Is registered in
INTROSPECTOR_MAPwith a symbol key - Belongs to one or both presets (
:standard,:full) - Results are cached with TTL + fingerprint invalidation
The Introspector orchestrator runs configured introspectors and merges results.
Five modules answer questions every introspector used to answer for itself:
- PathResolver - where a kind of app code lives:
app/<kind>, packs, and the in-repo code roots read from the tree (a directory holding its ownapp/plus a gemspec,plugin.rborlib/**/engine.rb), memoized per root - SourceScan - one walk over a kind of app source, across every directory
PathResolverresolves:pathsstats,eachreads,classesnames by the declared constant - EagerLoad - loads a directory's constants for a booted-tier walk, one file at a time, so an unloadable file costs only itself. A file Prism finds a syntax error in is never required, nor is one whose class body names its constant (a subclass, an includer); each is left out with the reason, which a model's or a controller's answer gives in its place. A tool that looks an app class up by name goes through
EagerLoad.constant, which loads it asconstantizewould and never requires such a file - GemLock - which gems the app resolved and at what version, read once per lockfile and matched by exact name across GEM, GIT and PATH
- PackageJson - which npm packages the app depends on, read once per
package.json: present means named independenciesordevDependencies, so anoverridespin is not a dependency, and@tailwindcss/vitecounts as tailwindcss
One more reads PostgreSQL's catalogs for the schema, the database stats and rails_runtime_info:
- PgPartitions - which tables are partitions, and each table's rows, bytes and index scans from
pg_stat_user_tablesandpg_stat_user_indexes, counting a partition toward its partitioned parent, so every surface names a partitioned table once
Two more answer a question a tool asks:
- PendingMigrations - which migration files are not in the applied set, from one derivation both the schema and migrations sections read
- ActionFilters - which filters apply to a controller or to one of its actions: own, inherited, skipped.
skippedholds unconditional skips only; a skip carryingif:/unless:leaves the filter inownorinheritedwith the condition on the record. Every controller surface reads its filter line from here, so no two answers can disagree
Four more answer for the app's databases and for what rails_query runs on them:
- DatabaseFamily - what a database is by its adapter's name: PostgreSQL (PostGIS too), MySQL (Trilogy and MariaDB too) or SQLite, else no family. A family owns its read-only transaction, its statement timeout, EXPLAIN, table sizes, row estimates and index usage. A runtime call on no family raises before anything reaches the database
- AppDatabases - every database the app has, listed once per run: the primary, the rest of the running environment's, those only another environment configures, then dumps no environment claims. Both tiers build it through one builder. It also leases a connection to a database configured here, through a connection handler of its own for the call
- SecretColumns - which columns
rails_querynever returns and a statement may not name, from one read of the leased database's schema. Anencryptscolumn is secret whateverquery_allowed_columnslists - SqlGate - whether
rails_queryruns a statement: the checks on its text, and on PostgreSQL the checks on its plan. It answers the comment-free text to run or a refusal with the reason
AST Engine
Ruby source is read with Prism. A regex still reads Ruby only in a case the AST-vs-regex rule allows, such as a prefilter the parse then checks, or over the text RubySource gives it: comments, =begin blocks and string bodies blanked to spaces with every line and offset kept, so a comment, a string or a heredoc cannot match. The readers that also run before the app boots (the install's read of the initializer and its guard, and the settings read without running the app) parse with the standard library's Ripper, since an app's bundle may pin Prism.
- AstCache - Thread-safe parse cache (
Concurrent::Map), keyed by the SHA256 of the file's content; a stat match answers without a read for a file already two seconds older than the read that recorded it - SourceIntrospector - Single-pass Prism Dispatcher walks the AST once, feeding every registered listener simultaneously
- Listeners - Associations, Validations, Scopes, Enums, Callbacks, Macros, Methods and Mixins are the default map for model analysis; the rest are used through targeted walks over schema dumps, migrations, Gemfiles, rake tasks and initializers, and
MethodCallListenerreports a named call with its arguments and options wherever one is asked for - Confidence - A listener that records one tags each record
[VERIFIED](static literals) or[INFERRED](dynamic expressions), and a record in a static-tier entry is capped at[STATIC], since no record can claim more than the tier that carries it
Tool Registry (lib/rails_ai_context/tools/base_tool.rb)
Auto-registration via Ruby's inherited hook:
BaseTool.inherited(subclass)fires when any file intools/defines a subclass- Subclass is appended to
@descendants(protected by@registry_mutex) BaseTool.registered_toolseager-loads all tool files and returns non-abstract classesBaseToolitself is markedabstract!- excluded from the registry- The ten classes that render a
rails_get_configsection callsection_renderer!.rails_get_configcalls them, so they stay out of the registry and are still callable from Ruby
Deadlock-free design: eager_load! walks Tools.constants and const_gets each one without holding the mutex, because const_get triggers Zeitwerk autoloading which calls inherited, which takes the mutex itself.
MCP Server (lib/rails_ai_context/server.rb)
Built on the official mcp Ruby SDK:
- Transports: stdio (default) or HTTP (Streamable HTTP via
MCP::Server::Transports::StreamableHTTPTransport) - Router (
WorkspaceServer, ADR-0012): the plugin's stdio serve in a folder of several apps, except on Windows, where that serve refuses the folder and names each app's--app-pathcommand. It answers the handshake and the lists itself, adds a requiredappargument to every tool, and hands each call to that app's own serve, aChildServerit starts at the app's first call - Proxy (
ChildServer.proxy): the plugin's serve in front of an app's bundled copy, passing every line on, so the session stays connected if that copy stops - Tools: all active tools (builtin + custom − skip_tools)
- Resources: 9 static resources + 5 dynamic VFS resource templates
- Instrumentation: bridges to
ActiveSupport::Notifications - Live Reload: watches files, invalidates caches, notifies clients
VFS (lib/rails_ai_context/vfs.rb)
Virtual File System for rails-ai-context:// URIs:
rails-ai-context://models/Post → model details + schema
rails-ai-context://controllers/Posts → actions, filters, params
rails-ai-context://controllers/Posts/index → action source
rails-ai-context://views/posts/show.html.erb → template content
rails-ai-context://routes/posts → filtered routes
Every resolve call introspects afresh, once the server has reloaded the app's code for any edit (see Caching).
Hydration Layer (lib/rails_ai_context/hydrators/)
Cross-tool semantic hydration (v5.3.0):
- ControllerHydrator - Parses controller source via Prism AST to detect model references, injects schema hints
- ViewHydrator - Maps
@post→Postby convention, injects schema hints - SchemaHintBuilder - Resolves model names to
SchemaHintvalue objects from cached context - HydrationFormatter - Renders hints as compact Markdown sections
- ModelHints - Resolves a set of model names to hint blocks once, so a name spelled two ways is not warned about or rendered twice
Result: controller and view tools automatically include relevant schema information without extra tool calls.
Serializers (lib/rails_ai_context/serializers/)
20 modules that format introspection output for different AI tools:
| Serializer | Output |
|---|---|
ContextFileSerializer |
Writes a run's files: the root files the LoadPlan picks, each AI tool's rules, and the JSON dump |
LoadPlan |
Which root files the chosen AI tools get and what each holds: the root content, an @AGENTS.md import, or nothing, so the content is written once into a file every chosen tool reads (AiTool#reads) |
RootFile |
The root context file, the same bytes at every path it lands at (AGENTS.md, CLAUDE.md, .github/copilot-instructions.md): compact, or full through MarkdownSerializer |
ClaudeRulesSerializer |
.claude/rules/*.md |
CursorRulesSerializer |
.cursor/rules/*.mdc, and takes the block an earlier release wrote out of .cursorrules |
CopilotInstructionsSerializer |
.github/instructions/*.instructions.md |
OpencodeRulesSerializer |
app/models/AGENTS.md, app/controllers/AGENTS.md (OpenCode and Codex) |
JsonSerializer |
.ai-context.json |
MarkdownSerializer |
The full-mode root file |
CompactSerializerHelper |
The compact root file's sections |
RuleScope |
When a rules file loads (every session, by path, or on request), written as each AI tool's frontmatter |
Budget |
Every size rule: the bytes per kind of file, the 240-character list line, and how many of each list a file names |
ModelSection |
The model list, rendered once at the density its file takes |
StackSections |
The header, gems, architecture and global before_actions, each rendered once at the density its file takes |
StackOverviewHelper |
Stack overview lines, the test command, and the rule-file write path four serializers share |
ToolGuideHelper |
The tools guide, each example in the one form the tool mode uses |
GuideExamples |
The model, controller and files the guide's examples name, the app's own where it has them |
SectionFacts |
The facts every surface states about an app - auth, assets, associations, the filter chain, an unread entry's row, the static-tier notice - each rendered in one place |
SectionMarkerWriter |
Writes a managed section into a file the user also owns, and takes one out |
Base |
Holds the context hash a serializer renders, and the run's LoadPlan |
CLI (exe/rails-ai-context, lib/rails_ai_context/cli/)
Thor-based CLI that works standalone (no Gemfile entry):
AppRoot- Decides which app a command reads before anything reads the working directory:--app-pathas given, else the working directory, else the nearest app root above it, else the one app below it. A root that has abin/railsand no app source reads the app thatbin/railsnames below it, else itstest/dummyorspec/dummyapp. Several below are refused by name, except by the plugin's serve, whichAppRoot.targethands the folder of apps to route (see MCP Server), andinit, which sets them all upEntryBoot- Boots the appAppRootchose for the standalone binary, or says which tier it fell back toRefusal- Where the plugin's serve cannot serve, answers the MCP handshake with no tools and the reason, so Claude Code does not skip the plugin; also the line parse and theinitializeanswer the router and the proxy shareToolRunner- Parses CLI args, resolves tool names, executes tools, formats output- Supports
--jsonmode for machine-readable output - Same 35 tools available as MCP and CLI
Path safety (lib/rails_ai_context/safe_path.rb, lib/rails_ai_context/view_file.rb)
- SafePath - Resolves a caller-supplied path once, in a fixed refusal order: traversal, sensitive name, realpath, containment, sensitive realpath, file, size.
BaseTool.safe_globis the globbed-path form, checking realpath, containment and the sensitive realpath on each path a pattern yields - ViewFile - Which file a view name means, and whether the app owns it, so no tool builds a template path itself
Caching
Four cache layers:
- Introspection cache (
BaseTool.SHARED_CACHE) - Mutex-protected, TTL + fingerprint invalidation - AST cache (
AstCache) -Concurrent::Map, SHA256 fingerprint per file, a stat shortcut for a settled file, bounded at 500 - Run cache (
RunCache) - thread-local, lives for oneIntrospector#callorgenerate_context: file lists, stats and directory answers every section would otherwise ask again - Session cache (
BaseTool.SESSION_CONTEXT) - Mutex-protected call history, resets on server restart
Every server - stdio, HTTP, or the endpoints mounted in the app - checks the files at the start of each tool call and resource read (BaseTool.refresh_if_files_changed!, through Fingerprinter::Snapshot), reloading the app's code and resetting the caches when they moved, so an answer sees every edit made before its call. That check runs outside the introspection cache's mutex, since a code reload waits for running calls, and a call shares only a check that began after it arrived. LiveReload watches the same files and tells clients when they change; it loads no code and drops no cache.
Fingerprinter (lib/rails_ai_context/fingerprinter.rb)
SHA256-based change detection:
- Watches:
app/,config/,db/,lib/,rakelib/,test/,spec/, the Gemfile and Gemfile.lock (orgems.rbandgems.locked),package.json,tsconfig.json,config.ru, the Rakefile - Computes a composite fingerprint from all watched files
- Used by introspection cache and live reload to detect actual changes
Fingerprinter::Snapshotanswers the same question before every call by stat alone, keeping each directory's listing while the directory's stat holds; a file young enough to have been written twice in one clock tick has its content compared too, and a directory linked in from the app's repository is followed as the readers follow it, its link asked where it leads at every look
Key design decisions
- Official MCP SDK - Not a custom protocol. Uses
mcpgem'sMCP::Tool,MCP::Server, transports. - Read-only tools - All 35 tools annotated as non-destructive. Defense-in-depth for query tool.
- Graceful degradation - Works without database (parses
schema.rborstructure.sql, or replays the migrations), without Brakeman, without ripgrep, without listen gem. - Zeitwerk autoloading - Files loaded on-demand.
require_relativeis kept for the few files that load before or outside the loader. - Diff-aware generation - Context file regeneration skips a file whose content is unchanged, the timestamp line aside.
- Section markers - Root file content wrapped in
<!-- BEGIN/END rails-ai-context -->to preserve user-added content.
Dependencies
| Gem | Purpose | Required? |
|---|---|---|
mcp |
MCP SDK - server, tools, transports | Yes |
prism |
AST parsing (stdlib in Ruby 3.3+) | Yes |
concurrent-ruby |
Thread-safe caches | Yes |
zeitwerk |
Autoloading | Yes |
thor |
CLI framework | Yes |
brakeman |
Security scanning | Optional |
listen |
File watching for live reload | Optional |
Decision records
- Derive Prism listener registration ourselves, not via prism's register_public_methods
- Static tier capability is declared per introspector, never auto-detected
- The two shared tool caches: what is a defect and what is intended
- The install e2e specs keep their examples; the fast specs took the load instead
- A workspace's MCP entries name their app by a relative path
- Strong params resolve a call as Ruby would run it
- Every install question has a flag, and only --prune removes files
- rails_query runs only on a database family it can guard
- rails_query stays in Ruby and takes dbhub's shapes
- One config tool with sections
- The Claude Code plugin runs the installed gem through ruby
- One plugin server serves every app in the session
- The lists that keep things back are a union on every tier