No release in over 3 years
Rails Agent Server provides a persistent background server for running Rails code without the overhead of booting Rails for each request. Perfect for AI agents that need fast Rails console access.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies
 Project Readme

Rails Agent Server

A persistent Rails server for AI agents that avoids boot overhead for repeated queries. Intended for AI agents like Claude Code that need fast Rails runner access without waiting for Rails to boot on every request.

Why This Gem?

When using AI coding assistants or automation tools with Rails applications, the agent often needs to run many small queries via bin/rails runner to understand the runtime behaviour or state. Using bin/rails runner for each query means booting Rails every time, which can typically take 5-10 seconds per query.

Rails Agent Server starts a persistent background server that keeps Rails loaded in memory. The first request takes the normal Rails boot time, but subsequent requests are almost instant.

Why Not bin/rails console?

AI agents can't easily interact with bin/rails console because:

  • Interactive TTY requirement: Rails console expects an interactive terminal (TTY) and won't accept input from standard pipes
  • No request/response protocol: There's no simple way to send a command and receive just its result back
  • Session complexity: Managing an interactive console session requires handling readline, prompt detection, and terminal control sequences
  • Output parsing: Console output includes prompts, formatting, and IRB metadata that's difficult to parse programmatically

Rails Agent Server provides a simple request/response interface over Unix sockets, making it trivial for AI agents to execute code and get clean results.

Why Not Spring?

Spring is Rails' official application preloader, but it's designed for different use cases.

How They Work

Spring keeps a preloaded Rails application in memory and uses fork() to create a new process for each command. When you run bin/spring rails runner, it forks the preloaded process, runs your code in isolation, and exits. Each invocation is stateless with a clean slate. This also means Spring can safely handle concurrent requests from multiple agents or parallel processes.

Rails Agent Server boots Rails once and keeps a single persistent session running. It accepts code over a Unix socket and evaluates it in the same long-running process. Variables and state persist between requests - like rails console, not rails runner. This means it's designed for single agent use - concurrent requests would share state unpredictably.

Both solve the "Rails is slow to boot" problem. Spring forks a fresh process for each command while Rails Agent Server runs code in a single persistent session.

How Rails Agent Server Works (Pseudocode)

# Server process (runs in background)
def run
  load_rails_environment        # Boot Rails once
  create_unix_socket           # Create socket file for communication
  
  loop do
    client = accept_connection  # Wait for code to execute
    code = client.read          # Read the code string
    output = capture_output do  # Capture stdout/stderr
      eval(code, TOPLEVEL_BINDING)  # Execute in persistent session
    end
    client.write(output)        # Send output back
    client.close
  end
end

# Client (called by rails_agent_server command)
def execute(code)
  start_server unless server_running?  # Auto-start if needed
  
  socket = connect_to_server
  socket.write(code)              # Send code to evaluate
  response = socket.read          # Get output back
  socket.close
  
  puts response                   # Display to user
end

The key insight: code runs in TOPLEVEL_BINDING of a persistent process, so variables and state carry over between requests, just like in rails console.

Spring is a viable option if it works well for your team. Rails Agent Server is for teams that prefer to not use Spring.

Why Not MCP (Model Context Protocol)?

MCP servers provide a structured way for AI agents to interact with systems through defined tools and resources. While MCP is excellent for complex, multi-step workflows and standardized interfaces, Rails Agent Server is preferable when:

  • Simplicity: You just need to run Rails code quickly without defining MCP tools and schemas
  • Flexibility: AI agents can execute arbitrary Rails code without being limited to predefined tool operations
  • Setup: No need to configure MCP server definitions, transport layers, or client-server communication
  • Performance: Direct command execution is faster than MCP's request/response protocol overhead
  • Token efficiency: MCP can consume many tokens for structured tool schemas and responses
  • Existing workflows: Works with agents that already know how to run shell commands

Rails Agent Server is a lightweight alternative that lets AI agents treat your Rails app like a fast REPL, while MCP is better suited for building formalized integrations with specific capabilities.

Installation

Option 1: Global Installation (Recommended for AI Agents)

Install the gem globally so it works with any Rails app without modifying Gemfiles:

gem install rails_agent_server

This allows AI agents to use the tool on any Rails project immediately.

Option 2: Add to Gemfile

Alternatively, add it to your application's Gemfile:

gem 'rails_agent_server', group: :development

And then execute:

bundle install

Agent Setup

Add this section to your project's CLAUDE.md or equivalent:

## Rails Console Access

This project uses `rails_agent_server` for fast Rails runner access without boot overhead.

When you need to query the database or run Rails code:
- Use `rails_agent_server 'YourCode.here'` instead of `bin/rails runner`
- First request auto-starts a persistent server (takes ~5 seconds)
- Subsequent requests are almost instant (no Rails boot time)
- Server stays running in background until you run `rails_agent_server stop`

Examples:
  rails_agent_server 'puts User.count'
  rails_agent_server 'puts Post.where(published: true).count'
  rails_agent_server 'puts User.find_by(email: "test@example.com")&.name'

Note: Use `bundle exec rails_agent_server` if the gem is in your Gemfile, or just `rails_agent_server` if installed globally.

Usage

Basic Commands

These commands are designed to be used by AI agents (like Claude Code) or automation tools, and not intended for manual use.

# Run a Ruby expression (auto-starts server if needed)
rails_agent_server 'puts User.count'

# Run code that prints output
rails_agent_server 'puts User.pluck(:email).join(", ")'

# Run a script file
rails_agent_server /path/to/script.rb

# Server management
rails_agent_server status                    # Check if server is running
rails_agent_server stop                      # Stop the background server
rails_agent_server restart                   # Restart the background server

Examples

# Database queries
rails_agent_server 'puts User.count'
rails_agent_server 'puts Post.where(published: true).pluck(:title)'
rails_agent_server 'puts User.find_by(email: "test@example.com")&.name'

# Inspect schema
rails_agent_server 'puts ActiveRecord::Base.connection.tables'
rails_agent_server 'puts User.column_names'

# Complex operations
rails_agent_server 'Rails.cache.clear; puts "Cache cleared"'

How It Works

  1. First Request: When you run rails_agent_server for the first time, it:

    • Spawns a background server process
    • Loads your Rails environment once
    • Creates a Unix socket for communication
    • Stores the PID for management
  2. Subsequent Requests: Each request:

    • Connects to the existing Unix socket
    • Sends code to execute
    • Receives the result instantly
    • No Rails boot time required
  3. Server Management: The server:

    • Runs in the background until explicitly stopped
    • Captures both printed output and expression results
    • Handles errors gracefully
    • Cleans up socket and PID files on exit

File Locations

By default, the server creates these files in your Rails application:

  • Socket: tmp/rails_agent_server.sock - Unix socket for communication
  • PID file: tmp/pids/rails_agent_server.pid - Process ID for management
  • Log file: log/rails_agent_server.log - Server output and errors

If not in a Rails directory, files are created in /tmp/.

Performance

  • First request: ~5-10 seconds (Rails boot time)
  • Subsequent requests: Almost instant (no boot overhead)
  • Memory: One Rails process running in background (~200-500MB depending on your app)

When to Restart

You should restart the server when:

  • You've changed model files or schema
  • You've updated initializers
  • You've modified environment configuration
  • The server is returning stale data
rails_agent_server restart

Limitations

  • Single agent only: The server processes one request at a time. Multiple agents or concurrent requests will be unpredictable due to shared state in the persistent session. Spring's fork-based approach handles concurrent requests safely by isolating each in its own process.
  • The server may need to be restarted to pick up some code changes
  • Only one server runs per Rails application (shared socket file)
  • Requires Unix sockets (macOS, Linux, WSL)

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install.

Testing

The test suite includes unit tests (fast, run in CI) and integration tests (slower, require process forking). By default, rake test runs only unit tests. See TESTING.md for details on running integration tests locally.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/andyw8/rails_agent_server.

License

The gem is available as open source under the terms of the MIT License.