Class: RailsActiveMcp::Sdk::Tools::SafeQueryTool

Inherits:
MCP::Tool
  • Object
show all
Defined in:
lib/rails_active_mcp/sdk/tools/safe_query_tool.rb

Class Method Summary collapse

Class Method Details

.call(model:, method:, server_context:, **options) ⇒ Object



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
# File 'lib/rails_active_mcp/sdk/tools/safe_query_tool.rb', line 46

def self.call(model:, method:, server_context:, **options)
  args = options.fetch(:args, [])
  where = options[:where]
  limit = options.fetch(:limit, 100)

  config = RailsActiveMcp.config
  executor = RailsActiveMcp::ConsoleExecutor.new(config)

  result = executor.execute_safe_query(
    model: model,
    method: method,
    args: args,
    where: where,
    limit: limit
  )

  if result[:success]
    output = []
    output << "Query: #{format_query(model, method, args, where)}"
    output << "Count: #{result[:count]}" if result[:count]
    output << "Result: #{result[:result].inspect}"

    MCP::Tool::Response.new([
                              { type: 'text', text: output.join("\n") }
                            ])
  else
    error_response(result[:error])
  end
end

.error_response(message) ⇒ Object



85
86
87
88
89
90
# File 'lib/rails_active_mcp/sdk/tools/safe_query_tool.rb', line 85

def self.error_response(message)
  MCP::Tool::Response.new(
    [{ type: 'text', text: message }],
    error: true
  )
end

.format_query(model, method, args, where) ⇒ Object



76
77
78
79
80
81
82
83
# File 'lib/rails_active_mcp/sdk/tools/safe_query_tool.rb', line 76

def self.format_query(model, method, args, where)
  prefix = if where.is_a?(Hash) && where.any?
             "#{model}.where(#{where.inspect})"
           else
             model.to_s
           end
  "#{prefix}.#{method}(#{args.join(', ')})"
end