Module: McpHelper

Defined in:
lib/stack-service-base/mcp/mcp_helper.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/stack-service-base/mcp/mcp_helper.rb', line 7

def self.included(base)
  base.class_eval do

    error McpProcessor::ParseError do |err|
      status err.status
      err.body
    end

    get '/mcp' do
      content_type :json
      MCP_PROCESSOR.root_endpoint
    end

    post '/mcp' do
      content_type 'text/event-stream'
      headers['Cache-Control'] = 'no-cache'
      headers['X-Accel-Buffering'] = 'no'
      headers['mcp-session-id'] = SecureRandom.uuid
      request.body&.rewind
      body = request.body.read.to_s

      response_body =
        begin
          MCP_PROCESSOR.rpc_endpoint(body)
        rescue McpProcessor::ParseError => e
          status e.status
          e.body
        end

      LOGGER.debug "request body: #{body}"
      LOGGER.debug "response body: #{response_body}"

      stream true do |s|
        s.callback { LOGGER.debug "stream closed: #{s}" }
        s << "event: message\ndata: #{response_body}\n\n"
        s.close
      end
    end
  end
end