Class: ActiveMcp::Server::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/active_mcp/server/fetcher.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_uri: nil, auth: nil) ⇒ Fetcher

Returns a new instance of Fetcher.



4
5
6
7
8
9
10
# File 'lib/active_mcp/server/fetcher.rb', line 4

def initialize(base_uri: nil, auth: nil)
  @base_uri = base_uri

  if auth
    @auth_header = "#{(auth[:type] == :bearer) ? "Bearer" : "Basic"} #{auth[:token]}"
  end
end

Instance Method Details

#call(params:) ⇒ Object



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
47
48
49
50
51
52
53
54
# File 'lib/active_mcp/server/fetcher.rb', line 12

def call(params:)
  return unless @base_uri

  require "net/http"

  unless @base_uri.is_a?(URI) || @base_uri.is_a?(String)
    Server.log_error("Invalid URI type", StandardError.new("URI must be a String or URI object"))
    return
  end

  begin
    uri = URI.parse(@base_uri.to_s)

    unless uri.scheme =~ /\Ahttps?\z/ && !uri.host.nil?
      Server.log_error("Invalid URI", StandardError.new("URI must have a valid scheme and host"))
      return
    end

    if defined?(Rails) && Rails.env.production? && uri.scheme != "https"
      Server.log_error("HTTPS is required in production environment", StandardError.new("Non-HTTPS URI in production"))
      return
    end
  rescue URI::InvalidURIError => e
    Server.log_error("Invalid URI format", e)
    return
  end

  request = Net::HTTP::Post.new(uri)
  request.body = JSON.generate(params)
  request["Content-Type"] = "application/json"
  request["Authorization"] = @auth_header

  begin
    response = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(request)
    end

    JSON.parse(response.body, symbolize_names: true)
  rescue => e
    Server.log_error("Error fetching resource_templates", e)
    nil
  end
end