Class: RailsAiContext::McpController

Inherits:
ActionController::API
  • Object
show all
Defined in:
app/controllers/rails_ai_context/mcp_controller.rb

Overview

Rails controller for serving MCP over Streamable HTTP. Alternative to the Rack middleware — integrates with Rails routing, authentication, and middleware stack.

Mount in routes: mount RailsAiContext::Engine, at: “/mcp”

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.mcp_transportObject

Class-level memoization — transport persists across requests. Thread-safe: MCP::Server and transport are stateless for reads.



20
21
22
23
24
25
26
27
# File 'app/controllers/rails_ai_context/mcp_controller.rb', line 20

def mcp_transport
  @transport_mutex.synchronize do
    @mcp_transport ||= begin
      server = RailsAiContext::Server.new(Rails.application, transport: :http).build
      MCP::Server::Transports::StreamableHTTPTransport.new(server)
    end
  end
end

.reset_transport!Object



29
30
31
# File 'app/controllers/rails_ai_context/mcp_controller.rb', line 29

def reset_transport!
  @transport_mutex.synchronize { @mcp_transport = nil }
end

Instance Method Details

#handleObject



10
11
12
13
14
15
# File 'app/controllers/rails_ai_context/mcp_controller.rb', line 10

def handle
  rack_response = self.class.mcp_transport.handle_request(request)
  self.status = rack_response[0]
  rack_response[1].each { |k, v| response.headers[k] = v }
  self.response_body = rack_response[2]
end