Class: ActiveMcp::ToolExecutor

Inherits:
Object
  • Object
show all
Defined in:
app/models/active_mcp/tool_executor.rb

Class Method Summary collapse

Class Method Details

.execute(params:, auth_info:) ⇒ Object



3
4
5
6
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'app/models/active_mcp/tool_executor.rb', line 3

def self.execute(params:, auth_info:)
  if params[:jsonrpc].present?
    tool_name = params[:params][:name]
    tool_params = params[:params][:arguments]
  else
    tool_name = params[:name]
    tool_params = params[:arguments]
  end
  
  unless tool_name
    return {
      isError: true,
      content: [
        {
          type: "text",
          text: "Invalid params: missing tool name",
        }
      ]
    }
  end

  tool_class = Tool.registered_tools.find do |tc|
    tc.tool_name == tool_name
  end
  
  unless tool_class
    return {
      isError: true,
      content: [
        {
          type: "text",
          text: "Tool not found: #{tool_name}",
        }
      ]
    }
  end
  
  unless tool_class.visible?(auth_info)
    return {
      isError: true,
      content: [
        {
          type: "text",
          text: "Unauthorized: Access to tool '#{tool_name}' denied",
        }
      ]
    }
  end

  if tool_params
    arguments = tool_params.permit!.to_hash.symbolize_keys.transform_values do |value|
      if !value.is_a?(String)
        value
      else
        value.match(/^\d+$/) ? value.to_i : value
      end
    end
  else
    arguments = {}
  end

  tool = tool_class.new
  validation_result = tool.validate_arguments(arguments)

  if validation_result.is_a?(Hash) && validation_result[:error]
    return {
      isError: true,
      content: [
        {
          type: "text",
          text: validation_result[:error],
        }
      ]
    }
  end
  
  # Execute the tool
  begin
    arguments[:auth_info] = auth_info if auth_info.present?
    
    return {
      content: [
        {
          type: "text",
          text: formatted(tool.call(**arguments.symbolize_keys))
        }
      ]
    }
  rescue => e
    return {
      isError: true,
      content: [
        {
          type: "text",
          text: "Error: #{e.message}",
        }
      ]
    }
  end
end

.formatted(object) ⇒ Object



104
105
106
107
108
109
110
111
112
113
# File 'app/models/active_mcp/tool_executor.rb', line 104

def self.formatted(object)
  case object
  when String
    object
  when Hash
    object.to_json
  else
    object.to_s
  end
end