Module: Legate::Web::ToolsUIRoutes

Defined in:
lib/legate/web/routes/tools_ui_routes.rb

Class Method Summary collapse

Class Method Details

.registered(app) ⇒ 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/legate/web/routes/tools_ui_routes.rb', line 7

def self.registered(app)
  # GET /tools - Display available native and MCP tools
  app.get '/tools' do
    logger.info('GET /tools route handler entered (from ToolsUIRoutes)')

    current_app_instance = self
    definition_store = current_app_instance.instance_variable_get(:@definition_store)

    # 1. Get Native Tools (already formatted)
     = Legate::GlobalToolManager.list_all_tools.map do |tool_meta|
      parameters_array = []
      if tool_meta[:parameters].is_a?(Hash) && !tool_meta[:parameters].empty?
        tool_meta[:parameters].each do |param_name, details|
          parameters_array << {
            name: param_name,
            type: details[:type],
            description: details[:description],
            required: details[:required]
          }
        end
      end
      tool_meta.merge(parameters: parameters_array, source: :native, source_detail: 'Native')
    end

    # 2. Get MCP Tools
    all_mcp_configs = []
    if definition_store
      begin
        agent_summaries = definition_store.list_definitions
        all_mcp_configs = agent_summaries.flat_map do |summary|
          mcp_json = summary[:mcp_servers_json]
          if mcp_json && !mcp_json.empty? && mcp_json != '[]'
            JSON.parse(mcp_json)
          else
            []
          end
        end.uniq
      rescue JSON::ParserError => e
        logger.error("Error parsing MCP JSON for /tools (from ToolsUIRoutes): #{e.message}")
      rescue Legate::DefinitionStore::StoreError => e
        logger.error("Store error fetching agent definitions for /tools (from ToolsUIRoutes): #{e.message}")
      end
    else
      logger.warn('Definition store not available for MCP tool discovery in /tools (from ToolsUIRoutes)')
    end

    mcp_tool_fetch_results = fetch_mcp_tools(all_mcp_configs || [])

     = []
    mcp_tool_fetch_results.each do |result|
      next unless result[:status] == :success && result[:tools]

      result[:tools].each do |mcp_tool_schema|
        parameters = []
        begin
          input_schema = mcp_tool_schema[:inputSchema]
          if input_schema&.is_a?(Hash)
            properties = input_schema['properties'] || {}
            required_props = input_schema['required'] || []
            parameters = Legate::Mcp::Util::SchemaConverter.json_to_legate(properties, required_props)
          end
        rescue StandardError => e
          logger.error("Error converting MCP schema for tool '#{mcp_tool_schema[:name]}' in /tools (from ToolsUIRoutes): #{e.message}")
        end
         << {
          name: mcp_tool_schema[:name].to_sym,
          description: mcp_tool_schema[:description] || '',
          parameters: parameters,
          source: :mcp,
          source_detail: "MCP (#{result[:server]})"
        }
      end
    end

    # 3. Set @native_tools for the current view requirements
    instance_variable_set(:@native_tools, .sort_by { |t| t[:name].to_s })

    # For future enhancement of tools.slim to show all tools:
    combined_tools_map = {}
    .each { |tool| combined_tools_map[tool[:name]] = tool }
    .each { |tool| combined_tools_map[tool[:name]] ||= tool }
    instance_variable_set(:@all_tools_list, combined_tools_map.values.sort_by { |t| t[:name].to_s })
    instance_variable_set(:@mcp_tool_results_for_view, mcp_tool_fetch_results) # For displaying fetch errors

    slim :tools
  end

  # GET /tools/:name - Display tool detail page (native or MCP)
  app.get '/tools/:name' do |name|
    logger.info("GET /tools/#{name} route handler entered (from ToolsUIRoutes)")
    tool_name_sym = name.to_sym

    current_app_instance = self
    definition_store = current_app_instance.instance_variable_get(:@definition_store)

    # 1. Try to find in native tools
     = Legate::GlobalToolManager.list_all_tools.find { |t| t[:name] == tool_name_sym }
    tool_to_display = nil

    if 
      parameters_array = []
      if [:parameters].is_a?(Hash) && ![:parameters].empty?
        [:parameters].each do |param_name, details|
          parameters_array << {
            name: param_name,
            type: details[:type],
            description: details[:description],
            required: details[:required]
          }
        end
      end
      tool_to_display = .merge(parameters: parameters_array, source: :native,
                                                   source_detail: 'Native')
    else
      # 2. Not native, try to find in MCP tools
      all_mcp_configs = []
      if definition_store
        begin
          agent_summaries = definition_store.list_definitions
          all_mcp_configs = agent_summaries.flat_map do |summary|
            mcp_json = summary[:mcp_servers_json]
            if mcp_json && !mcp_json.empty? && mcp_json != '[]'
              JSON.parse(mcp_json)
            else
              []
            end
          end.uniq
        rescue JSON::ParserError => e
          logger.error("Error parsing MCP JSON for /tools/#{name} (from ToolsUIRoutes): #{e.message}")
        rescue Legate::DefinitionStore::StoreError => e
          logger.error("Store error fetching agent definitions for /tools/#{name} (from ToolsUIRoutes): #{e.message}")
        end
      else
        logger.warn("Definition store not available for MCP tool discovery in /tools/#{name} (from ToolsUIRoutes)")
      end

      mcp_tool_fetch_results = fetch_mcp_tools(all_mcp_configs || [])

      mcp_tool_fetch_results.each do |result|
        next unless result[:status] == :success && result[:tools]

        tool_data = result[:tools].find { |t| t[:name].to_s == name || t[:name].to_sym == tool_name_sym }
        next unless tool_data

        parameters = []
        begin
          input_schema = tool_data[:inputSchema]
          if input_schema&.is_a?(Hash)
            properties = input_schema['properties'] || {}
            required_props = input_schema['required'] || []
            parameters = Legate::Mcp::Util::SchemaConverter.json_to_legate(properties, required_props)
          end
        rescue StandardError => e
          logger.error("Error converting MCP schema for tool '#{tool_data[:name]}' in /tools/#{name} (from ToolsUIRoutes): #{e.message}")
        end
        tool_to_display = {
          name: tool_data[:name].to_sym,
          description: tool_data[:description] || '',
          parameters: parameters,
          source: :mcp,
          source_detail: "MCP (#{result[:server]})"
        }
        break
      end
    end

    if tool_to_display
      instance_variable_set(:@tool, tool_to_display)
      logger.debug("Found tool metadata for '#{name}': #{tool_to_display.inspect}")
      slim :tool_detail
    else
      logger.warn("Tool '#{name}' not found anywhere (from ToolsUIRoutes).")
      status 404
      slim(:error_404,
           locals: { title: 'Tool Not Found', message: "Tool definition for '#{name}' not found." })
    end
  end

  # GET /tools/:name/download - Download native tool as Ruby file
  app.get '/tools/:name/download' do |name|
    logger.info("Received request to download tool '#{name}' as Ruby file")
    tool_name_sym = name.to_sym

    # Check if it's a native tool
    tool_class = Legate::GlobalToolManager.find_class(tool_name_sym)
    halt 400, 'Only native tools can be downloaded as Ruby files. MCP tools cannot be exported.' unless tool_class

    # Generate Ruby code
    require 'legate/tool_code_generator'
    ruby_code = Legate::ToolCodeGenerator.generate(tool_name_sym)

    halt 404, 'Tool not found or could not generate code.' unless ruby_code

    content_type 'application/x-ruby'
    attachment "#{name.to_s.gsub(/[^a-zA-Z0-9_-]/, '_')}.rb"
    ruby_code
  end
end