Architecture

How rails-ai-context is built, and why: its modules and the request lifecycle.

Tools Reference · Introspectors · Security · Custom Tools


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:

The Introspector orchestrator runs configured introspectors and merges results.

Five modules answer questions every introspector used to answer for itself:

One more reads PostgreSQL's catalogs for the schema, the database stats and rails_runtime_info:

Two more answer a question a tool asks:

Four more answer for the app's databases and for what rails_query runs on them:

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.

Tool Registry (lib/rails_ai_context/tools/base_tool.rb)

Auto-registration via Ruby's inherited hook:

  1. BaseTool.inherited(subclass) fires when any file in tools/ defines a subclass
  2. Subclass is appended to @descendants (protected by @registry_mutex)
  3. BaseTool.registered_tools eager-loads all tool files and returns non-abstract classes
  4. BaseTool itself is marked abstract! - excluded from the registry
  5. The ten classes that render a rails_get_config section call section_renderer!. rails_get_config calls 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:

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):

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):

Path safety (lib/rails_ai_context/safe_path.rb, lib/rails_ai_context/view_file.rb)

Caching

Four cache layers:

  1. Introspection cache (BaseTool.SHARED_CACHE) - Mutex-protected, TTL + fingerprint invalidation
  2. AST cache (AstCache) - Concurrent::Map, SHA256 fingerprint per file, a stat shortcut for a settled file, bounded at 500
  3. Run cache (RunCache) - thread-local, lives for one Introspector#call or generate_context: file lists, stats and directory answers every section would otherwise ask again
  4. 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:

Key design decisions

  1. Official MCP SDK - Not a custom protocol. Uses mcp gem's MCP::Tool, MCP::Server, transports.
  2. Read-only tools - All 35 tools annotated as non-destructive. Defense-in-depth for query tool.
  3. Graceful degradation - Works without database (parses schema.rb or structure.sql, or replays the migrations), without Brakeman, without ripgrep, without listen gem.
  4. Zeitwerk autoloading - Files loaded on-demand. require_relative is kept for the few files that load before or outside the loader.
  5. Diff-aware generation - Context file regeneration skips a file whose content is unchanged, the timestamp line aside.
  6. 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

← AI Tool Setup · Introspectors →

Back to Home

Decision records