|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# FastMcp - Model Context Protocol for Rails |
| 4 | +# This initializer sets up the MCP middleware in your Rails application. |
| 5 | +# |
| 6 | +# In Rails applications, you can use: |
| 7 | +# - ActionTool::Base as an alias for FastMcp::Tool |
| 8 | +# - ActionResource::Base as an alias for FastMcp::Resource |
| 9 | +# |
| 10 | +# All your tools should inherit from ApplicationTool which already uses ActionTool::Base, |
| 11 | +# and all your resources should inherit from ApplicationResource which uses ActionResource::Base. |
| 12 | + |
| 13 | +# Mount the MCP middleware in your Rails application |
| 14 | +# You can customize the options below to fit your needs. |
| 15 | +require "fast_mcp" |
| 16 | + |
| 17 | +FastMcp.mount_in_rails( |
| 18 | + Rails.application, |
| 19 | + name: Rails.application.class.module_parent_name.underscore.dasherize, |
| 20 | + version: "1.0.0", |
| 21 | + path_prefix: "/mcp", # This is the default path prefix |
| 22 | + messages_route: "messages", # This is the default route for the messages endpoint |
| 23 | + sse_route: "sse", # This is the default route for the SSE endpoint |
| 24 | + # Add allowed origins below, it defaults to Rails.application.config.hosts |
| 25 | + allowed_origins: [ "localhost", "127.0.0.1", "[::1]", "b69340af24ec.ngrok-free.app", /.*\.example\.com/ ], |
| 26 | + localhost_only: false, # Set to false to allow connections from other hosts |
| 27 | + # whitelist specific ips to if you want to run on localhost and allow connections from other IPs |
| 28 | + # allowed_ips: ['127.0.0.1', '::1'] |
| 29 | + # authenticate: true, # Uncomment to enable authentication |
| 30 | + # auth_token: 'your-token', # Required if authenticate: true |
| 31 | +) do |server| |
| 32 | + Rails.application.config.after_initialize do |
| 33 | + # FastMcp will automatically discover and register: |
| 34 | + # - All classes that inherit from ApplicationTool (which uses ActionTool::Base) |
| 35 | + # - All classes that inherit from ApplicationResource (which uses ActionResource::Base) |
| 36 | + server.register_tools(*ApplicationTool.descendants) |
| 37 | + server.register_resources(*ApplicationResource.descendants) |
| 38 | + # alternatively, you can register tools and resources manually: |
| 39 | + # server.register_tool(MyTool) |
| 40 | + # server.register_resource(MyResource) |
| 41 | + end |
| 42 | +end |
0 commit comments