{"id":31250549,"url":"https://github.com/ganjooh/rails-ast-mcp-server","last_synced_at":"2026-05-01T18:33:19.235Z","repository":{"id":311710316,"uuid":"1044705579","full_name":"ganjooh/rails-ast-mcp-server","owner":"ganjooh","description":"Intelligent code indexing and retrieval system for Ruby on Rails projects with MCP integration","archived":false,"fork":false,"pushed_at":"2025-09-01T07:34:22.000Z","size":382,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-11T17:58:11.536Z","etag":null,"topics":["ai-tools","ast","claude","code-indexing","developer-tools","mcp","model-context-protocol","rails","ruby","ruby-on-rails"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ganjooh.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-26T05:07:27.000Z","updated_at":"2025-09-01T07:34:23.000Z","dependencies_parsed_at":null,"dependency_job_id":"648e22fd-5ea3-4016-af89-0e32709a12a5","html_url":"https://github.com/ganjooh/rails-ast-mcp-server","commit_stats":null,"previous_names":["ganjooh/rails-mcp-indexer","ganjooh/rails-ast-mcp-server"],"tags_count":12,"template":false,"template_full_name":null,"purl":"pkg:github/ganjooh/rails-ast-mcp-server","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ganjooh%2Frails-ast-mcp-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ganjooh%2Frails-ast-mcp-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ganjooh%2Frails-ast-mcp-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ganjooh%2Frails-ast-mcp-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ganjooh","download_url":"https://codeload.github.com/ganjooh/rails-ast-mcp-server/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ganjooh%2Frails-ast-mcp-server/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32508901,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-30T13:12:12.517Z","status":"online","status_checked_at":"2026-05-01T02:00:05.856Z","response_time":64,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-tools","ast","claude","code-indexing","developer-tools","mcp","model-context-protocol","rails","ruby","ruby-on-rails"],"created_at":"2025-09-23T05:29:59.487Z","updated_at":"2026-05-01T18:33:19.209Z","avatar_url":"https://github.com/ganjooh.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Rails AST MCP Server\n\nAn intelligent MCP (Model Context Protocol) server for Ruby on Rails projects that provides AST-based code parsing, knowledge graph navigation, and advanced analysis capabilities. Features native Ruby AST parsing with automatic fallback to regex-based parsing when Ruby is not available.\n\n## Why Use Rails AST MCP Server?\n\n### Advantages Over Vanilla Claude Code / Cursor\n\n| Feature | Vanilla Claude Code / Cursor | Rails AST MCP Server |\n|---------|------------------------------|-------------------|\n| **Rails DSL Understanding** | Basic text search | Full understanding of associations, validations, callbacks, scopes |\n| **Symbol Search** | File-by-file scanning | Indexed database with instant FTS5 search |\n| **Call Graph Analysis** | Not available | Trace method dependencies and call relationships |\n| **Test Discovery** | Manual search | Automatic test file detection |\n| **Performance** | Searches entire codebase each time | Pre-indexed SQLite database with sub-second queries |\n| **Memory Usage** | Loads files into context | Efficient database queries, minimal context usage |\n| **Rails Patterns** | Generic code understanding | Rails-specific: models, controllers, services, jobs, etc. |\n| **AST Parsing** | Not available | Native Ruby AST parsing (when Ruby installed) |\n\n### Key Benefits\n\n1. **Context Efficiency**: Instead of loading entire files into Claude's context window, you can query specific symbols and relationships\n2. **Rails Intelligence**: Understands Rails DSL - knows that `has_many :posts` creates methods like `posts`, `posts=`, `posts\u003c\u003c`, etc.\n3. **Speed**: Pre-indexed database means instant searches vs scanning files every time\n4. **Accurate Symbol Detection**: Native Ruby AST parsing (when available) ensures 100% accurate symbol detection\n\n## Features\n\n- 🔍 **Smart Symbol Search**: Find classes, methods, modules across your Rails codebase\n- 📊 **Call Graph Analysis**: Trace method calls and dependencies\n- 🧪 **Test Discovery**: Automatically find related test files\n- 📁 **Rails-aware**: Understands Rails conventions and patterns\n- 🚀 **Hybrid Parsing**: Native Ruby AST when available, regex fallback otherwise\n- ⚡ **Fast Search**: SQLite FTS5 full-text search for instant results\n- 🎯 **Context Efficient**: Minimizes token usage by returning only relevant code\n- 🗄️ **Schema Awareness**: Parses db/schema.rb to understand database structure\n- 🔗 **Association Suggestions**: Automatically suggests Rails associations from foreign keys\n- ✅ **Validation Generation**: Suggests validations based on database constraints\n\n## Quick Start\n\n### Claude Code\n\n```bash\n# Add the server for your Rails project (requires full path)\nclaude mcp add rails-ast npx -- -y rails-ast-mcp-server /path/to/your/rails/project\n\n# Example:\nclaude mcp add rails-ast npx -- -y rails-ast-mcp-server /Users/you/sources/my-rails-app\n\n# Restart Claude Code to activate the server\n```\n\n**Important:** Always use the full absolute path to your Rails project\n\n## Configuration\n\n### Command Line Arguments\n\nThe server accepts a single argument for the repository path:\n\n```bash\n# Specify the Rails project path as an argument\nnpx rails-ast-mcp-server /path/to/rails/project\n\n# Or use current directory\nnpx rails-ast-mcp-server .\n```\n\n### Environment Variables\n\nYou can also configure the server using environment variables:\n\n| Variable | Description | Default | Example |\n|----------|-------------|---------|---------|\n| `REPO_PATH` | Path to your Rails project | Current directory (`.`) | `/Users/me/myapp` |\n| `DB_PATH` | SQLite database location | `{project}/.rails-index/repo.db` | `/tmp/rails.db` |\n| `RUBY_AST_PARSER` | Custom Ruby parser path | Built-in parser | `/opt/parser.rb` |\n| `AUTO_INDEX` | Enable auto-indexing on startup | `true` | `false` |\n\n```bash\n# Example with environment variables\nREPO_PATH=/path/to/rails/app DB_PATH=/tmp/index.db npx rails-ast-mcp-server\n\n# Disable auto-indexing\nAUTO_INDEX=false npx @hiteshganjoo/rails-mcp-indexer\n```\n\n### Auto-Indexing Features (v2.1.0+)\n\nThe indexer now includes intelligent auto-indexing capabilities:\n\n#### 1. **Automatic Index on Startup**\n- Automatically indexes your Rails project when the server starts\n- Only indexes if:\n  - Database doesn't exist (first run)\n  - Repository path has changed\n  - Database is empty\n- Skips indexing if the existing index is valid\n- Can be disabled with `AUTO_INDEX=false`\n\n#### 2. **Project-Specific Database**\n- Database is now stored at `{project}/.rails-index/repo.db` by default\n- Each Rails project gets its own index\n- No more conflicts when switching between projects\n\n#### 3. **Incremental Indexing**\n- Only re-indexes files that have changed since last index\n- Checks file modification times vs last index time\n- Much faster than full reindex for large projects\n\n#### 4. **Smart Reindexing Detection**\n- Automatically detects when a full reindex is needed:\n  - When switching to a different Rails project\n  - When the database is corrupted or missing\n  - When explicitly requested via the `reindex` tool\n\n### Project-Specific Configuration\n\nCreate a `.mcp.json` file in your Rails project root:\n\n```json\n{\n  \"rails-indexer\": {\n    \"repoPath\": \".\",\n    \"dbPath\": \".rails-index/repo.db\",\n    \"autoIndex\": true\n  }\n}\n```\n\n## Available Tools\n\n### 🔍 search_symbols\n\nSearch for symbols (classes, methods, modules) in your codebase.\n\n```typescript\n{\n  \"query\": \"User\",           // Search query\n  \"k\": 10,                   // Number of results (default: 10)\n  \"file_types\": [\"model\"]    // Optional: Filter by file types\n}\n```\n\n### 📝 get_snippet\n\nExtract code snippets from files.\n\n```typescript\n{\n  \"file_path\": \"app/models/user.rb\",\n  \"start_line\": 10,          // Optional\n  \"end_line\": 20,            // Optional\n  \"symbol_name\": \"validate\"  // Optional: Extract specific symbol\n}\n```\n\n### 📊 call_graph\n\nAnalyze call relationships between methods.\n\n```typescript\n{\n  \"symbol\": \"User.authenticate\",\n  \"direction\": \"both\",       // \"callers\" | \"callees\" | \"both\"\n  \"depth\": 2                 // Analysis depth\n}\n```\n\n### 🔄 find_similar\n\nFind code patterns similar to a given snippet.\n\n```typescript\n{\n  \"code_snippet\": \"validates :email, presence: true\",\n  \"k\": 5,                   // Number of results\n  \"min_similarity\": 0.7     // Minimum similarity score\n}\n```\n\n### 🧪 find_tests\n\nFind test files related to an implementation file.\n\n```typescript\n{\n  \"file_path\": \"app/models/user.rb\"\n}\n```\n\n### 🔄 reindex\n\nReindex the codebase.\n\n```typescript\n{\n  \"paths\": [\"app/models\"],  // Optional: Specific paths\n  \"full\": false             // Full reindex\n}\n```\n\n### 🗄️ db_tables\n\nList all database tables from schema.rb.\n\n```typescript\n// No parameters required\n```\n\n### 📊 db_table\n\nGet detailed information about a database table including columns, indexes, and constraints.\n\n```typescript\n{\n  \"table_name\": \"users\"\n}\n```\n\n### 🔗 db_table_relations\n\nGet foreign key relationships for a table.\n\n```typescript\n{\n  \"table_name\": \"orders\"\n}\n```\n\n### 💡 db_suggest_associations\n\nSuggest Rails associations and validations based on database schema.\n\n```typescript\n{\n  \"table_name\": \"posts\"\n}\n```\n\nReturns:\n- Rails association declarations (belongs_to, has_many, has_one)\n- Validation suggestions based on constraints\n- Model name inference\n\n## Database Schema Support\n\nThe indexer automatically parses `db/schema.rb` to provide database-aware features:\n\n### Automatic Schema Indexing\n- Parses `db/schema.rb` during reindex\n- Extracts tables, columns, indexes, and foreign keys\n- Stores schema metadata in SQLite for fast queries\n\n### Rails Association Generation\nBased on foreign keys in your schema, the indexer suggests:\n- `belongs_to` associations for foreign key columns\n- `has_many` or `has_one` based on unique constraints\n- Proper `dependent` options from ON DELETE rules\n- `inverse_of` relationships\n\n### Validation Suggestions\nAutomatically suggests validations based on:\n- NOT NULL constraints → `presence: true`\n- Unique indexes → `uniqueness: true`\n- String column limits → `length: { maximum: X }`\n- Numeric columns → `numericality` validations\n\n## Rails File Type Recognition\n\nThe indexer automatically recognizes these Rails patterns:\n\n| Type | Pattern | Example |\n|------|---------|---------|\n| `model` | `app/models/**/*.rb` | User, Post, Comment |\n| `controller` | `app/controllers/**/*.rb` | UsersController |\n| `service` | `app/services/**/*.rb` | AuthenticationService |\n| `job` | `app/jobs/**/*.rb`, `app/sidekiq/**/*.rb` | SendEmailJob |\n| `policy` | `app/policies/**/*.rb` | UserPolicy |\n| `mailer` | `app/mailers/**/*.rb` | UserMailer |\n| `helper` | `app/helpers/**/*.rb` | ApplicationHelper |\n| `concern` | `app/*/concerns/**/*.rb` | Searchable |\n| `spec` | `spec/**/*_spec.rb`, `test/**/*_test.rb` | user_spec.rb |\n| `migration` | `db/migrate/**/*.rb` | add_email_to_users.rb |\n\n## How It Works\n\n1. **Parsing**: Hybrid approach - native Ruby AST parser when Ruby is available, regex fallback otherwise\n2. **Indexing**: Stores parsed data in SQLite with FTS5 for fast search\n3. **MCP Protocol**: Exposes tools via Model Context Protocol for AI assistants\n\n### Ruby Support (Optional)\n\nThe indexer works **without Ruby installation**, but having Ruby installed provides more accurate parsing:\n\n| Ruby Version | Support Level | Features |\n|--------------|---------------|----------|\n| **No Ruby** | ✅ Full Support | Regex-based parser, all features work |\n| **Ruby 2.7+** | ✅ Enhanced | Native AST parsing via `parser` gem |\n| **Ruby 3.3+** | ✅ Enhanced | Native AST parsing via `prism` (built-in) |\n\nWhen Ruby is detected during installation, the package automatically:\n1. Detects your Ruby version\n2. Installs appropriate parser gems\n3. Uses native AST parsing for 100% accurate symbol detection\n4. Falls back to regex parsing if native parsing fails\n\n## Architecture\n\n```\n┌──────────────────┐     ┌──────────────────┐\n│  Claude/AI Agent │────▶│   MCP Protocol   │\n└──────────────────┘     └──────────────────┘\n                                │\n                                ▼\n                         ┌──────────────────┐\n                         │  Rails MCP Server│\n                         └──────────────────┘\n                                │\n                ┌───────────────┼───────────────┐\n                ▼               ▼               ▼\n         ┌──────────────┐ ┌──────────────┐ ┌──────────────┐\n         │ Ruby Parser  │ │   Indexer    │ │   Database   │\n         └──────────────┘ └──────────────┘ └──────────────┘\n                │               │               │\n                └───────────────┼───────────────┘\n                                ▼\n                        ┌──────────────────┐\n                        │  Rails Codebase  │\n                        └──────────────────┘\n```\n\n## Development\n\n### Prerequisites\n\n- Node.js 18+\n- TypeScript 5+\n\n### Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/ganjooh/rails-ast-mcp-server\ncd rails-ast-mcp-server\n\n# Install dependencies\nnpm install\n\n# Build the project\nnpm run build\n\n# Test with sample Rails app\nREPO_PATH=./sample_rails_app npm start\n```\n\n### Testing\n\n```bash\n# Run tests\nnpm test\n\n# Test with MCP Inspector\nnpx @modelcontextprotocol/inspector npm start\n```\n\n## Usage Examples\n\n### Real-World Advantages in Claude Code\n\n#### Without Rails MCP Indexer (Vanilla Claude Code)\n```\nUser: \"Find all authentication methods in my Rails app\"\nClaude: *Searches through multiple files, uses significant context*\n\"Let me search through your codebase... \nReading app/models/user.rb...\nReading app/controllers/application_controller.rb...\nReading app/controllers/sessions_controller.rb...\"\n[Uses 5000+ tokens just to find methods]\n```\n\n#### With Rails MCP Indexer\n```\nUser: \"Find all authentication methods in my Rails app\"\nClaude: *Instantly queries the index*\nFound 5 authentication-related methods:\n- User.authenticate (app/models/user.rb:37)\n- SessionsController#create (app/controllers/sessions_controller.rb:8)\n- ApplicationController#authenticate_user! (app/controllers/application_controller.rb:15)\n[Uses only 200 tokens with precise results]\n```\n\n### Common Use Cases\n\n#### 1. Finding Symbol Definitions\n```bash\n# Ask Claude Code:\n\"Where is the User.authenticate method defined?\"\n# Rails MCP Indexer instantly returns: app/models/user.rb:37-41\n\n# Vanilla Claude Code would need to:\n# - Search through all model files\n# - Parse each file to find the method\n# - Use significant context tokens\n```\n\n#### 2. Understanding Model Relationships\n```bash\n# Ask Claude Code:\n\"What associations does the User model have?\"\n# Rails MCP Indexer knows:\n# - has_many :posts\n# - has_many :comments, through: :posts\n# - has_one :profile\n# - belongs_to :organization\n\n# Vanilla Claude Code would need to load and parse the entire User model\n```\n\n#### 3. Finding Related Tests\n```bash\n# Ask Claude Code:\n\"Find tests for the User model\"\n# Rails MCP Indexer instantly returns:\n# - spec/models/user_spec.rb\n# - spec/requests/users_spec.rb\n# - test/models/user_test.rb\n\n# Vanilla Claude Code would manually search through spec/ and test/ directories\n```\n\n### Direct Tool Usage\n\n```javascript\n// Example: Search for authentication-related symbols\nconst result = await mcpClient.callTool('search_symbols', {\n  query: 'authenticate',\n  k: 5,\n  file_types: ['model', 'controller']\n});\n\n// Example: Get call graph for a method\nconst graph = await mcpClient.callTool('call_graph', {\n  symbol: 'User.authenticate',\n  direction: 'both',\n  depth: 2\n});\n\n// Example: Find similar validation patterns\nconst similar = await mcpClient.callTool('find_similar', {\n  code_snippet: 'validates :email, presence: true, uniqueness: true',\n  k: 5\n});\n```\n\n## Troubleshooting\n\n### Server not connecting\n\n1. Check Node.js version: `node --version` (should be 18+)\n2. Verify paths: Ensure REPO_PATH points to valid Rails project\n3. Check logs: Run with `DEBUG=* npm start`\n\n### Index not updating\n\n1. Run reindex: Use the `reindex` tool with `full: true`\n2. Check permissions: Ensure write access to DB_PATH directory\n3. Verify file patterns: Check if your Rails structure matches expected patterns\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nMIT License - see [LICENSE](LICENSE) file for details.\n\n## Support\n\n- Issues: [GitHub Issues](https://github.com/ganjooh/rails-ast-mcp-server/issues)\n- Discussions: [GitHub Discussions](https://github.com/ganjooh/rails-ast-mcp-server/discussions)\n\n## Acknowledgments\n\nBuilt with [Model Context Protocol SDK](https://github.com/modelcontextprotocol/sdk) for seamless AI integration.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fganjooh%2Frails-ast-mcp-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fganjooh%2Frails-ast-mcp-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fganjooh%2Frails-ast-mcp-server/lists"}