feat(ee): Captain custom http tools (#12584)

To test this out, use the following PR:
https://github.com/chatwoot/chatwoot/pull/12585

---------

Co-authored-by: Pranav <pranavrajs@gmail.com>
This commit is contained in:
Shivam Mishra
2025-10-06 20:23:15 +05:30
committed by GitHub
parent a8aefa0c73
commit 8bbb8ba5a4
17 changed files with 1299 additions and 92 deletions

View File

@@ -8,12 +8,12 @@ module Concerns::CaptainToolsHelpers
TOOL_REFERENCE_REGEX = %r{\[[^\]]+\]\(tool://([^/)]+)\)}
class_methods do
# Returns all available agent tools with their metadata.
# Returns all built-in agent tools with their metadata.
# Only includes tools that have corresponding class files and can be resolved.
#
# @return [Array<Hash>] Array of tool hashes with :id, :title, :description, :icon
def available_agent_tools
@available_agent_tools ||= load_agent_tools
def built_in_agent_tools
@built_in_agent_tools ||= load_agent_tools
end
# Resolves a tool class from a tool ID.
@@ -26,12 +26,12 @@ module Concerns::CaptainToolsHelpers
class_name.safe_constantize
end
# Returns an array of all available tool IDs.
# Convenience method that extracts just the IDs from available_agent_tools.
# Returns an array of all built-in tool IDs.
# Convenience method that extracts just the IDs from built_in_agent_tools.
#
# @return [Array<String>] Array of available tool IDs
def available_tool_ids
@available_tool_ids ||= available_agent_tools.map { |tool| tool[:id] }
# @return [Array<String>] Array of built-in tool IDs
def built_in_tool_ids
@built_in_tool_ids ||= built_in_agent_tools.map { |tool| tool[:id] }
end
private

View File

@@ -0,0 +1,84 @@
module Concerns::SafeEndpointValidatable
extend ActiveSupport::Concern
FRONTEND_HOST = URI.parse(ENV.fetch('FRONTEND_URL', 'http://localhost:3000')).host.freeze
DISALLOWED_HOSTS = ['localhost', /\.local\z/i].freeze
included do
validate :validate_safe_endpoint_url
end
private
def validate_safe_endpoint_url
return if endpoint_url.blank?
uri = parse_endpoint_uri
return errors.add(:endpoint_url, 'must be a valid URL') unless uri
validate_endpoint_scheme(uri)
validate_endpoint_host(uri)
validate_not_ip_address(uri)
validate_no_unicode_chars(uri)
end
def parse_endpoint_uri
# Strip Liquid template syntax for validation
# Replace {{ variable }} with a placeholder value
sanitized_url = endpoint_url.gsub(/\{\{[^}]+\}\}/, 'placeholder')
URI.parse(sanitized_url)
rescue URI::InvalidURIError
nil
end
def validate_endpoint_scheme(uri)
return if uri.scheme == 'https'
errors.add(:endpoint_url, 'must use HTTPS protocol')
end
def validate_endpoint_host(uri)
if uri.host.blank?
errors.add(:endpoint_url, 'must have a valid hostname')
return
end
if uri.host == FRONTEND_HOST
errors.add(:endpoint_url, 'cannot point to the application itself')
return
end
DISALLOWED_HOSTS.each do |pattern|
matched = if pattern.is_a?(Regexp)
uri.host =~ pattern
else
uri.host.downcase == pattern
end
next unless matched
errors.add(:endpoint_url, 'cannot use disallowed hostname')
break
end
end
def validate_not_ip_address(uri)
# Check for IPv4
if /\A\d+\.\d+\.\d+\.\d+\z/.match?(uri.host)
errors.add(:endpoint_url, 'cannot be an IP address, must be a hostname')
return
end
# Check for IPv6
return unless uri.host.include?(':')
errors.add(:endpoint_url, 'cannot be an IP address, must be a hostname')
end
def validate_no_unicode_chars(uri)
return unless uri.host
return if /\A[\x00-\x7F]+\z/.match?(uri.host)
errors.add(:endpoint_url, 'hostname cannot contain non-ASCII characters')
end
end

View File

@@ -0,0 +1,78 @@
module Concerns::Toolable
extend ActiveSupport::Concern
def tool(assistant)
custom_tool_record = self
tool_class = Class.new(Captain::Tools::HttpTool) do
description custom_tool_record.description
custom_tool_record.param_schema.each do |param_def|
param param_def['name'].to_sym,
type: param_def['type'],
desc: param_def['description'],
required: param_def.fetch('required', true)
end
end
tool_class.new(assistant, self)
end
def build_request_url(params)
return endpoint_url if endpoint_url.blank? || endpoint_url.exclude?('{{')
render_template(endpoint_url, params)
end
def build_request_body(params)
return nil if request_template.blank?
render_template(request_template, params)
end
def build_auth_headers
return {} if auth_none?
case auth_type
when 'bearer'
{ 'Authorization' => "Bearer #{auth_config['token']}" }
when 'api_key'
if auth_config['location'] == 'header'
{ auth_config['name'] => auth_config['key'] }
else
{}
end
else
{}
end
end
def build_basic_auth_credentials
return nil unless auth_type == 'basic'
[auth_config['username'], auth_config['password']]
end
def format_response(raw_response_body)
return raw_response_body if response_template.blank?
response_data = parse_response_body(raw_response_body)
render_template(response_template, { 'response' => response_data })
end
private
def render_template(template, context)
liquid_template = Liquid::Template.parse(template, error_mode: :strict)
liquid_template.render(context.deep_stringify_keys, registers: {}, strict_variables: true, strict_filters: true)
rescue Liquid::SyntaxError, Liquid::UndefinedVariable, Liquid::UndefinedFilter => e
Rails.logger.error("Liquid template error: #{e.message}")
raise "Template rendering failed: #{e.message}"
end
def parse_response_body(body)
JSON.parse(body)
rescue JSON::ParserError
body
end
end